﻿using Autofac.Core;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection.PortableExecutable;
using System.Threading.Tasks;
using VOL.Core.Controllers.Basic;
using VOL.Core.Filters;
using VOL.Core.ObjectActionValidator;
using VOL.Core.Services;
using VOL.Entity.DomainModels;
using VOL.System.IRepositories;
using VOL.System.IServices;

using VOL.Core.Enums;
using VOL.Core.Utilities;
using Org.BouncyCastle.Crypto.IO;
using VOL.WebApi.Controllers.WorkOrder;
using NPOI.HPSF;
using NPOI.HSSF.Util;
using VOL.Core.Configuration;
using Microsoft.Extensions.Caching.Memory;
using System.Net;
using VOL.Core.BaseProvider;
using VOL.Core.Extensions;
using VOL.Core.ManageUser;
using VOL.Core.CacheManager;
using VOL.System.Services;
using VOL.Entity.VM;
using Microsoft.Extensions.Configuration;
using NPOI.HSSF.UserModel;
using AutoMapper;
using EasyNetQ.Internals;
using Newtonsoft.Json.Linq;
using S7.Net;
using VOL.WebApi.Extensions;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;
using Tea;
using AlibabaCloud.SDK.Dysmsapi20170525.Models;
using NPOI.HSSF.Record;
using VOL.Core.BaseInterface;
using System.Net.Mail;
using Org.BouncyCastle.Crypto.Engines;
using System.Data.Common;
using System.Diagnostics;
using System.IO;


using System.Diagnostics;
using TDengine.Driver;
using TDengine.Driver.Client;
using Confluent.Kafka;
using FluentFTP.Helpers;
using System.Numerics;
using Org.BouncyCastle.Asn1.Tsp;
using System.Collections.Concurrent;
using DocumentFormat.OpenXml.Math;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Information;
using RFID.UHFReader;
using System.Threading;
using Microsoft.AspNetCore.SignalR;
using VOL.WebApi.Controllers.Hubs;
using DocumentFormat.OpenXml;
using System.Globalization;
using System.Text;
using System.Configuration;
using DocumentFormat.OpenXml.Spreadsheet;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using VOL.Core.DBManage;
using MQTTnet.Client;
using MQTTnet.Packets;
using MQTTnet;
using MQTTnet.Server;
using MQTTnet.Protocol;
using DocumentFormat.OpenXml.Office2019.Excel.RichData2;
using MediatR;



namespace VOL.WebApi.Controllers
{
    //public partial class EQU_COM_DEFINITION_TASK_DETECTIONService

    [AllowAnonymous, ApiController]
    [ApiExplorerSettings(GroupName = "v1")]
    [Route("A_UpperComputer")]
    public partial class A_UpperComputerController :
    //ApiBaseController<Iupper_work_orderService>
    ApiBaseController<ISys_UserService>
    {
        private static IMemoryCache _cacheNew = new MemoryCache(new MemoryCacheOptions());
        // 线程安全的队列，用于缓存RabbitMQ消息
        private static ConcurrentQueue<string> _messageQueue = new ConcurrentQueue<string>();

        private readonly Iupper_workpieceRepository _service;//访问业务代码
        private readonly IHttpContextAccessor _httpContextAccessor;
        private ISys_UserRepository _userRepository;
        private ISys_UserService userService;
        private ICacheService _cache;
        private readonly IMapper _mapper;
        private readonly IHubContext<ChatHub> _hubContext;
        private readonly IMediator _mediator;
        MqttFactory factory = new MqttFactory();
        IMqttClient _client =null;

        [ActivatorUtilitiesConstructor]
        public A_UpperComputerController(
            ISys_UserService service,
            Iupper_workpieceRepository serviceIupper_workpie,
            IHttpContextAccessor httpContextAccessor, ISys_UserRepository userRepository,
               ICacheService cahce, IHubContext<ChatHub> hubContext//, IMapper mapper
            ,IMediator mediator
          )// : base(service)
        : base("System", "System", "Sys_User", service)
        {
            _mediator = mediator;
            _service = serviceIupper_workpie;
            _httpContextAccessor = httpContextAccessor;
            _userRepository = userRepository;
            userService = new Sys_UserService(_userRepository);
            _cache = cahce;
                   _hubContext=hubContext;


            // 创建对象映射工具
            MapperConfiguration configuration = new MapperConfiguration(options =>
            {
                options.CreateMap<V_EQU_TOOL_ORDER, ToDoDto>();
                options.CreateMap<V_EQU_TOOL_ORDER, V_EQU_TOOL_ORDERTDD>();
                options.CreateMap<EQU_TOOL, EQU_TOOL_Dto>();
                options.CreateMap<INTE_SHELVES, INTE_SHELVES_Dto>();
                options.CreateMap<upper_work_order, upper_work_orderVM>();
                options.CreateMap<EQU_COM_DEFINITION_TASK, EQU_COM_DEFINITION_TASK_LOG>();
            });
            _mapper = configuration.CreateMapper();
            // _mapper =mapper;
            _client = factory.CreateMqttClient();
        }

        #region mediator


        /// <summary>
        /// mqtt
        /// </summary>
        /// <param name="topic"></param>
        /// <param name="msginput"></param>
        /// <returns></returns>
        [HttpGet, Route("EventTest")]
        public async Task<IActionResult> EventTest()
        {
            _mediator.Publish(new EQU_EQUIPMENT() { EquipmentNameZH="test"});
            return Ok("");
        }
        #endregion
        #region by guoyuguo 2024.8.14 
        ///// <summary>
        ///// 工单绑定
        ///// </summary>
        ///// <param name="id"></param>
        ///// <param name="machineUnit"></param>
        ///// <returns></returns>
        //[HttpGet, Route("GetCncInfo")]
        //public IActionResult GetCncInfo(int id, int machineUnit = 0)
        //{

        //    var bollrs = true;
        //    var msg = string.Empty;
        //    try
        //    {
        //        string idstr=id.ToString();
        //        upper_work_order uwo = _service.Find<upper_work_order>(t => t.work_order_number.Contains( idstr)).FirstOrDefault();                //new { Machine = "ma", WorkOrder = "workOrder" };
        //        if (uwo == null)
        //        {
        //            uwo = new upper_work_order() { };

        //            Logger.Info(VOL.Core.Enums.LoggerType.Search, null, bollrs ? "Ok" : msg);
        //            return Json(uwo);
        //        }
        //        upper_workpiece piece = _service.Find<upper_workpiece>(t => t.id == uwo.workpiece_id).FirstOrDefault();
        //        upper_machine machine = _service.Find<upper_machine>(t => t.id == piece.machine).FirstOrDefault();
        //      //  upper_work_orderVM workOrderVM = new upper_work_orderVM();
        //        var workOrderVM = _mapper.Map<upper_work_orderVM>(uwo);
        //        workOrderVM.Workpiece=piece;
        //        CncInfo cncInfo = new CncInfo()
        //        {
        //            Machine = machine,
        //            WorkOrder = workOrderVM
        //        };

        //        Logger.Info(VOL.Core.Enums.LoggerType.Search, null, bollrs ? "Ok" : msg);
        //        return Json(cncInfo);

        //    }
        //    catch (Exception ex)
        //    {
        //        msg = ex.Message;
        //        bollrs = false;
        //    }
        //    Logger.Info(VOL.Core.Enums.LoggerType.Search, null, bollrs ? "Ok" : msg);
        //    return Json(null);
        //}
        /// <summary>
        /// 根据条件进行刀具匹配查找
        /// </summary>
        /// <param name="toolHandle"></param>
        /// <param name="toolCollet"></param>
        /// <param name="width"></param>
        /// <param name="length"></param>
        /// <param name="r"></param>
        /// <param name="machineUnit"></param>
        /// <param name="workPieceHeight"></param>
        /// <returns></returns>
        [HttpGet, Route("GetToolByCenterCondition")]
        public IActionResult GetToolByCenterCondition(string toolHandle, string toolCollet, decimal width, decimal length, decimal r, int machineUnit, decimal workPieceHeight)
        {

            var bollrs = true;
            var msg = string.Empty;
            try
            {
                upper_machine upperMachine = _service.Find<upper_machine>(t => t.unit == machineUnit).FirstOrDefault();
                upper_tool tool = _service.Find<upper_tool>(a => a.location != 0 && a.location != null && a.use_status == 1
                                                            && a.handle_type == toolHandle
                                                       && a.collet_type == toolCollet
                                                        && a.R == r
                                                        && a.knife_width == width
                                                        && upperMachine.tool_height - a.reality_pairing_length > workPieceHeight
                                                        && a.knife_length == length).OrderBy(x => x.program_seq).FirstOrDefault();

                if (tool != null)
                {
                    if (tool.use_status == 1)
                    {
                        return Json(tool);
                    }
                    else
                    {
                        //如果原本的刀使用了，重新匹配新的刀
                        var searchTool = _service.Find<upper_tool>(a => a.location != 0 && a.location != null && a.use_status == 1
                                                               && a.handle_type == toolHandle
                                                           && a.collet_type == toolCollet
                                                             && a.reality_knife_width == width
                                                            && a.reality_knife_length >= tool.reality_knife_length
                                                            && upperMachine.tool_height - a.reality_pairing_length > workPieceHeight
                                                            && a.reality_knife_length <= tool.reality_knife_length + 5).OrderBy(a => a.reality_knife_length).OrderBy(x => x.program_seq).FirstOrDefault();

                        return Json(searchTool);
                    }
                }
                else
                {
                    //如果没有匹配到刀，去刀库里拿到匹配的刀
                    var searchTool = _service.Find<upper_tool>(a => a.location != 0 && a.location != null && a.location == 1
                                                           && a.handle_type == toolHandle
                                                           && a.collet_type == toolCollet
                                                            && a.reality_knife_width == width
                                                           && a.reality_knife_length >= length
                                                           && upperMachine.tool_height - a.reality_pairing_length > workPieceHeight
                                                           && a.reality_knife_length <= length + 5).OrderBy(a => a.reality_knife_length).OrderBy(x => x.program_seq).FirstOrDefault();

                    Logger.Info(VOL.Core.Enums.LoggerType.Search, null, bollrs ? "Ok" : msg);
                    return Json(searchTool);
                }


            }
            catch (Exception ex)
            {
                msg = ex.Message;
                bollrs = false;
            }
            Logger.Info(VOL.Core.Enums.LoggerType.Search, null, bollrs ? "Ok" : msg);
            return Json(null);
        }


        //public void SetUpperToolStatus(UpperTool tool)
        //{
        //    using (var context = new NetcoredevContext())
        //    {
        //        UpperTool changedTool = context.UpperTools.Where(a => a.Id == tool.Id).FirstOrDefault();
        //        changedTool.UseStatus = tool.UseStatus;
        //        context.SaveChanges();
        //    }
        //}
        /// <summary>
        /// 任务是否继续做
        /// </summary>
        /// <param name="workOrderId"></param>
        /// <returns></returns>
        [HttpGet, Route("IsWorkOn")]
        public IActionResult IsWorkOn(int workOrderId)
        {

            var bollrs = true;
            var msg = string.Empty;
            try
            {
                var workordersCount = _service.Find<upper_work_order>(a => a.process_Status == 1).Count(); //context.UpperWorkOrders.Include(a => a.Workpiece);
                if (workordersCount > 0)//判断是否有紧急任务
                {
                    var emergentMachines = _service.Find<upper_work_order>(a => a.process_Status == 1 && a.work_order_id == workOrderId).FirstOrDefault();//获取紧急机床
                    upper_workpiece currentWorkPiece = _service.Find<upper_workpiece>(a => a.id == emergentMachines.workpiece_id.Value).FirstOrDefault();
                    if (currentWorkPiece.machine > 0)
                    {
                        // 测试用改成true  return false;
                        return Json(true);
                    }
                    else
                    {
                        return Json(true);
                    }
                }
                else
                {
                    return Json(true);
                }

            }
            catch (Exception ex)
            {
                msg = ex.Message;
                bollrs = false;
            }
            Logger.Info(VOL.Core.Enums.LoggerType.Search, null, bollrs ? "Ok" : msg);
            return Json(bollrs);
        }

        ///// <summary>
        ///// 获取工件By ID
        ///// </summary>
        ///// <param name="workOrderId"></param>
        ///// <returns></returns>
        //public UpperWorkpiece? GetWorkPiece(int workOrderId)
        //{
        //    using (var context = new NetcoredevContext())
        //    {
        //        return context.UpperWorkOrders.Where(a => a.WorkOrderId == workOrderId).Include(a => a.Workpiece).Select(a => a.Workpiece).FirstOrDefault();
        //    }
        //}
        /// <summary>
        /// 设备是否在运行
        /// </summary>
        /// <param name="machineUnit"></param>
        /// <returns></returns>
        [HttpPost, Route("IsMachineRunning")]
        public async Task<IActionResult> IsMachineRunning(int machineUnit)
        {

            var bollrs = true;
            var msg = string.Empty;
            try
            {
                EQU_EQUIPMENT eQU_EQUIPMENT = _service.Find<EQU_EQUIPMENT>(a => a.unit == machineUnit).FirstOrDefault();

                if (eQU_EQUIPMENT != null)
                {
                    eQU_EQUIPMENT.UpperProgramOn = DateTime.Now;
                    _service.DbContext.Update<EQU_EQUIPMENT>(eQU_EQUIPMENT);
                    await _service.SaveChangesAsync();
                    Logger.Info(VOL.Core.Enums.LoggerType.Search, null, true ? "Ok" : msg);
                    return Json(true);
                }
                else
                {
                    Logger.Info(VOL.Core.Enums.LoggerType.Search, null, false ? "Ok" : msg);
                    return Json(false);
                }

            }
            catch (Exception ex)
            {
                msg = ex.Message;
                bollrs = false;
            }
            Logger.Info(VOL.Core.Enums.LoggerType.Search, null, bollrs ? "Ok" : msg);
            return Json(bollrs);
        }



        ///// <summary>
        ///// 改变设备状态
        ///// </summary>
        ///// <param name="machineUnit"></param>
        ///// <param name="isUsed"></param>
        //public void ChangeMachineStatus(int machineUnit, bool isUsed)
        //{
        //    using (var context = new NetcoredevContext())
        //    {
        //        UpperMachine machine = context.UpperMachines.Where(a => a.Unit == machineUnit).FirstOrDefault();
        //        machine.UseStatus = isUsed;
        //        context.SaveChanges();
        //    }
        //}

        ///// <summary>
        ///// 改变工单状态
        ///// </summary>
        ///// <param name="id"></param>
        ///// <param name="status"></param>
        //public void ChangeWorkOrderStatus(int id, uint status)
        //{
        //    using (var context = new NetcoredevContext())
        //    {
        //        UpperWorkOrder machine = context.UpperWorkOrders.Where(a => a.WorkOrderId == id).FirstOrDefault();
        //        machine.ProcessStatus = status;
        //        context.SaveChanges();
        //    }
        //}

        ///// <summary>
        ///// 行程检查
        ///// </summary>
        ///// <param name="machineUnit"></param>
        ///// <param name="workOrderId"></param>
        ///// <returns></returns>
        //public bool XingChengCheck(int machineUnit, int workOrderId)
        //{
        //    using (var context = new NetcoredevContext())
        //    {
        //        UpperWorkOrder workOrder = context.UpperWorkOrders.Where(a => a.WorkOrderId == workOrderId).Include(a => a.Workpiece).FirstOrDefault();
        //        UpperMachine machine = context.UpperMachines.Where(a => a.Unit == machineUnit).FirstOrDefault();

        //        return workOrder.Workpiece.WorkpieceWidth < machine.ItineraryY;

        //    }
        //}
        #endregion
        #region by guoyuguo 2024.8.27   采集 SCADA
        /// <summary>
        /// 设备上位机以10s为周期调用该接口，报告线体各具体设备在线、离线状态；
        /// 当设备上位机和PLC连接正常时，上报在线（即true），否则上报离线（即false）
        /// 0：自动运行; 1：待机; 2：正常停机; 3：故障停机; 4：待料;5：满料；
        /// </summary>
        /// <param name="equVM"></param>
        /// <returns></returns>
        [HttpPost, Route("EquToMesHeartbeat")]
        public async Task<ApiResponse> EquToMesHeartbeat([FromBody] EquOnLineVM equVM)
        {
            var bollrs = true;
            var msg = string.Empty;
            try
            {
                EQU_EQUIPMENT eQU_EQUIPMENT = _service.Find<EQU_EQUIPMENT>(t => t.EquipmentCode == equVM.EquipmentCode).FirstOrDefault();
                if (eQU_EQUIPMENT == null)
                {

                    msg = "设备不存在";
                    Logger.Info(VOL.Core.Enums.LoggerType.Error, null, bollrs ? "False" : msg);
                    return new ApiResponse(false, msg);
                }


                eQU_EQUIPMENT.IsOnline = equVM.IsOnline;
                eQU_EQUIPMENT.UpperProgramOn = DateTime.Now;
                _service.DbContext.Update<EQU_EQUIPMENT>(eQU_EQUIPMENT);
                await _service.SaveChangesAsync();
                Logger.Info(VOL.Core.Enums.LoggerType.Success, null, bollrs ? "Ok" : equVM.ToString());
                return new ApiResponse(true, eQU_EQUIPMENT);

            }
            catch (Exception ex)
            {
                msg = ex.Message;
                bollrs = false;
                Logger.Info(VOL.Core.Enums.LoggerType.Search, null, bollrs ? "False" : msg);
                return new ApiResponse(false, msg);
            }

        }
        /// <summary>
        /// 设备状态
        /// 当设备状态发生变化时，设备上位机调用该接口，报告具体设备的状态；若设备状态未发生变化时，不允许一直调用该接口
        /// 0：自动运行; 1：待机; 2：正常停机; 3：故障停机; 4：待料;5：满料；
        /// </summary>
        /// <param name="EquipmentCode"></param>
        /// <returns></returns>
        [HttpPost, Route("GetEquSatus")]
        public async Task<ApiResponse> GetEquSatus([FromBody] EquStateVM equVM)
        {
            var msg = string.Empty;
            var result= new ApiResponse(true,"");
            var bollrs = true;
            await PreventAPI.Instance.PreventConcurrentAsync("key", async () => {
                // 你的异步代码
                try
                {
                    var eQU_EQUIPMENT = await _service.FindAsyncFirst<EQU_EQUIPMENT>(t => t.EquipmentCode == equVM.EquipmentCode);
                    if (eQU_EQUIPMENT == null)
                    {
                        eQU_EQUIPMENT = await _service.FindAsyncFirst<EQU_EQUIPMENT>(t => t.unit == equVM.Unit);
                        if (eQU_EQUIPMENT == null)
                        {
                            msg = "设备不存在";
                            Logger.Info(VOL.Core.Enums.LoggerType.Error, null, bollrs ? "False" : msg);
                            result = new ApiResponse(false, msg);
                            return result;
                        }
                        else
                        {
                            if (eQU_EQUIPMENT.EquipmentCode != "SLK_001")
                            {
                                eQU_EQUIPMENT.LastUpdateOn = DateTime.Now;

                                eQU_EQUIPMENT.StateCode = equVM.StateCode;
                                eQU_EQUIPMENT.CurrentOrder = equVM.OrderCode;
                            }

                        }
                    }
                    else
                    {

                        eQU_EQUIPMENT.LastUpdateOn = DateTime.Now;

                        eQU_EQUIPMENT.StateCode = equVM.StateCode;
                        eQU_EQUIPMENT.CurrentOrder = equVM.OrderCode;

                    }

                    _service.DbContext.Update<EQU_EQUIPMENT>(eQU_EQUIPMENT);

                    await _service.SaveChangesAsync();
                    Logger.Info(VOL.Core.Enums.LoggerType.Success, null, bollrs ? "Ok" : equVM.ToString());
                    result = new ApiResponse(true, eQU_EQUIPMENT);
                
                    return result;

                }
                catch (Exception ex)
                {
                    msg = ex.Message;
                    bollrs = false;
                    Logger.Info(VOL.Core.Enums.LoggerType.Search, null, bollrs ? "False" : msg);
                  
                    result = new ApiResponse(false, msg);
                    return result;
                }

               
            });


            return result;
        }

        /// <summary>
        /// 获取设备信息CNC
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("GetEquCNC")]
        public async Task<ApiResponse> GetEquCNC()
        {

            var bollrs = true;
            var msg = string.Empty;
            try
            {
                var eQU_EQUIPMENTs = await _service.FindAsync<EQU_EQUIPMENT>(t => t.unit > 0); //await _service.DbContext.Set<EQU_EQUIPMENT>().Where(t=>t.unit>0); ///await _service.Find<EQU_EQUIPMENT>(t=>t.unit>0);
                var li = new List<EquStateVM>();
                foreach (var item in eQU_EQUIPMENTs)
                {
                    li.Add(new EquStateVM
                    {
                        OrderCode = item.CurrentOrder,
                        EquipmentCode = item.EquipmentCode,
                        Unit = item.unit,
                        MachineType = item.machine_type,
                        Host = item.host,
                        Port = item.port,
                        NcType = item.nc_type,
                        NcCardNo = item.nc_card_no
                    });
                }

                return new ApiResponse(true, li);
            }
            catch (Exception ex)
            {
                msg = ex.Message;
                bollrs = false;
                Logger.Info(VOL.Core.Enums.LoggerType.Search, null, bollrs ? "False" : msg);
                return new ApiResponse(false, msg);
            }

        }
        /// <summary>
        /// PLC获取信息对比
        /// </summary>
        /// <param name="rfidCode"></param>
        /// <returns></returns>
        [HttpPost, Route("FirstToolEquPLC")]
        public async Task<ApiResponse> FirstToolEquPLC(string rfidCode)
        {

            var bollrs = true;
            var msg = string.Empty;
            try
            {
                var data = await userService.FirstToolEquNew(rfidCode, _mapper);
                Logger.Info(VOL.Core.Enums.LoggerType.Success, null, bollrs ? "Ok" : data.Message);
                //return new ApiResponse(true, data);
                return data;

            }
            catch (Exception ex)
            {
                msg = ex.Message;
                bollrs = false;
                Logger.Info(VOL.Core.Enums.LoggerType.Search, null, bollrs ? "False" : msg);
                return new ApiResponse(false, msg);
            }
        }
        /// <summary>
        /// 刀具测量-RFID 读出绑定的刀具信息
        /// </summary>
        /// <param name="rfidCode"></param>
        /// <param name="_mapper"></param>
        /// <returns></returns>
        [HttpPost, Route("FirstToolEqu")]
        public async Task<ApiResponse> FirstToolEqu(string rfidCode)
        {

            var bollrs = true;
            var msg = string.Empty;
            try
            {
                var data = await userService.FirstToolEqu(rfidCode, _mapper);
                Logger.Info(VOL.Core.Enums.LoggerType.Success, null, bollrs ? "Ok" : data.Message);
                //return new ApiResponse(true, data);
                return data;

            }
            catch (Exception ex)
            {
                msg = ex.Message;
                bollrs = false;
                Logger.Info(VOL.Core.Enums.LoggerType.Search, null, bollrs ? "False" : msg);
                return new ApiResponse(false, msg);
            }
        }
        /// <summary>
        /// 刀具测量-RFID 更新刀具信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost, Route("UpdateToolEquByRfid")]
        public async Task<ApiResponse> UpdateToolEquByRfid([FromBody] EQU_TOOL_Dto model)
        {

            var bollrs = true;
            var msg = string.Empty;
            try
            {

                var data = await userService.UpdateToolEquByRfid(model, _mapper);
                Logger.Info(VOL.Core.Enums.LoggerType.Success, null, bollrs ? "Ok" : data.Message);
                if (model.CheckResult == 1)
                {
                    MQHelper.MQSendMsg(model.RfidCode, MQqueue.Equ_SendToolCheck.ToString());
                }
                return data;

            }
            catch (Exception ex)
            {
                msg = ex.Message;
                bollrs = false;
                Logger.Info(VOL.Core.Enums.LoggerType.Search, null, bollrs ? "False" : msg);
                return new ApiResponse(false, msg);
            }
        }
        /// <summary>
        /// 进站
        /// </summary>
        /// <param name="equVM"></param>
        /// <returns></returns>
        [HttpPost, Route("Inbound")]
        public IActionResult Inbound(EquVM equVM)
        {

            var bollrs = true;
            var msg = string.Empty;
            try
            {
                EQU_EQUIPMENT eQU_EQUIPMENT = _service.Find<EQU_EQUIPMENT>(t => t.EquipmentCode == equVM.EquipmentCode).FirstOrDefault();
                if (eQU_EQUIPMENT == null)
                {

                    msg = "设备不存在";
                    Logger.Info(VOL.Core.Enums.LoggerType.Error, null, bollrs ? "False" : msg);
                    return Json(msg);
                }

                MANU_EXECUTION mANU_EXECUTION = _service.Find<MANU_EXECUTION>(t => t.Equipment_Id == eQU_EQUIPMENT.Id.ToString()).FirstOrDefault();
                if (mANU_EXECUTION == null)
                {
                    MANU_EXECUTION mANU_EXECUTIONNew = new MANU_EXECUTION();
                    mANU_EXECUTIONNew.SubPathNo = equVM.SubPathNo;
                    //mANU_EXECUTIONNew.OrderCode=equVM.OrderCode;
                    mANU_EXECUTIONNew.Equipment_Id = eQU_EQUIPMENT.Id.ToString();
                    _service.DbContext.Add<MANU_EXECUTION>(mANU_EXECUTIONNew);

                }
                else
                {
                    mANU_EXECUTION.Equipment_Id = eQU_EQUIPMENT.Id.ToString();
                    mANU_EXECUTION.SubPathNo = equVM.SubPathNo;
                    _service.DbContext.Update<MANU_EXECUTION>(mANU_EXECUTION);
                }
                _service.SaveChanges();
                Logger.Info(VOL.Core.Enums.LoggerType.Success, null, bollrs ? "Ok" : equVM.ToString());
                return Ok(equVM);

            }
            catch (Exception ex)
            {
                msg = ex.Message;
                bollrs = false;
                Logger.Info(VOL.Core.Enums.LoggerType.Search, null, bollrs ? "False" : msg);
                return Json(msg);
            }

        }
        #endregion
        #region by guoyuguo 2024.9.3
        /// <summary>
        /// WebApi登陆(设备)
        /// </summary>
        /// <param name="loginInfo"></param>
        /// <returns></returns>
        [HttpPost, Route("LoginEqu")]
        public async Task<IActionResult> LoginEqu([FromBody] LoginInfo loginInfo)
        {
            return Json(await userService.LoginEqu(loginInfo));
        }
        #endregion

        #region by guoyuguo 2024.11.5 停止
        /// <summary>
        /// 启动
        /// </summary>
        /// <param name="taskOptions"></param>
        /// <returns></returns>
        [Route("start1"), HttpPost]
        [ActionPermission(ActionPermissionOptions.Update)]
        public async Task<object> Start([FromBody] MANU_EXECUTION taskOptions)
        {
            //return Content(DateTime.Now.ToString("yyyy-MM-dd HH:mm:sss"));
            return await Service.Start(taskOptions);
        }
        /// <summary>
        /// 暂停
        /// </summary>
        /// <param name="taskOptions"></param>
        /// <returns></returns>
        [Route("pause"), HttpPost]
        [ActionPermission(ActionPermissionOptions.Update)]
        public async Task<object> Pause([FromBody] MANU_EXECUTION taskOptions)
        {

            return await Service.Pause(taskOptions);
        }
        /// <summary>
        /// 紧急暂停
        /// </summary>
        /// <param name="taskOptions"></param>
        /// <returns></returns>
        [Route("stop"), HttpPost]
        [ActionPermission(ActionPermissionOptions.Update)]
        public async Task<object> Stop([FromBody] MANU_EXECUTION taskOptions)
        {
            // return Content(DateTime.Now.ToString("yyyy-MM-dd HH:mm:sss"));
            return await Service.Stop(taskOptions);
        }
        /// <summary>
        /// 终止
        /// </summary>
        /// <param name="taskOptions"></param>
        /// <returns></returns>
        [Route("termination"), HttpPost]
        [ActionPermission(ActionPermissionOptions.Update)]
        public async Task<object> Termination([FromBody] MANU_EXECUTION taskOptions)
        {
            //return Content(DateTime.Now.ToString("yyyy-MM-dd HH:mm:sss"));
            return await Service.Termination(taskOptions);
        }

        /// <summary>
        /// 标记弃用任务
        /// </summary>
        /// <param name="taskOptions"></param>
        /// <returns></returns>
        [Route("taskreceive"), HttpPost]
        [ActionPermission(ActionPermissionOptions.Update)]
        public async Task<object> TaskReceive([FromBody] Equ_TaskReceive taskOptions)
        {

            return await Service.Equ_MarkTask(taskOptions);
        }
        /// <summary>
        /// 继续加工（上位机忽略）
        /// </summary>
        /// <param name="taskOptions"></param>
        /// <returns></returns>
        [Route("taskcontinue"), HttpPost]
        //[ActionPermission(ActionPermissionOptions.Update)]
        public async Task<object> TaskContinue([FromBody] Equ_TaskReceive taskOptions)
        {
            return await Service.TaskContinue(taskOptions);
        }
        /// <summary>
        /// 生成
        /// </summary>
        /// <param name="taskOptions"></param>
        /// <returns></returns>

        [Route("taskgenerate"), HttpPost]
        [ActionPermission(ActionPermissionOptions.Update)]
        public async Task<object> Taskgenerate([FromBody] Taskgenerate taskOptions)
        {
            return await Service.Taskgenerate(taskOptions);
        }
        /// <summary>
        /// 标记弃用任务（程序 ）
        /// </summary>
        /// <param name="taskOptions"></param>
        /// <returns></returns>
        [Route("taskreceiveprogame"), HttpPost]
        [ActionPermission(ActionPermissionOptions.Update)]
        public async Task<object> TaskReceiveProgame([FromBody] Equ_TaskReceive taskOptions)
        {

            return await Service.Equ_MarkTask(taskOptions, "6");
        }
        #endregion
        #region by guoyuguo 2024.9.5 调度系统
        /// <summary>
        /// MES自动生成任务处理 只允许192.168.110.1网段执行
        /// </summary>
        /// <returns></returns>
        [ApiTask]
        [HttpPost, Route("ExePro_MES_Auto_Generate_Task")]
        public IActionResult ExePro_MES_Auto_Generate_Task()
        {
            var rs = new WebResponseContent();
            var isConnectUpdate1 = userService.IsIpConnect("192.168.1.160");
            if (isConnectUpdate1 == true)
            {
                rs.Message = $"192.168.1.160 不会执行！";
                rs.Status = false;
                return Json(rs);
            }
            rs = userService.ExePro_MES_Auto_Generate_Task();
            return Json(rs);
        }
        /// <summary>
        /// Ready
        /// </summary>
        /// <param name="equTaskSendReady"></param>
        /// <returns></returns>
        [HttpPost, Route("Equ_SendTASKReady")]
        public async Task<IActionResult> Equ_SendTASKReady([FromBody] Equ_TaskSendReady equTaskSendReady)
        {
            var rs = await userService.Equ_SendTASKReady(equTaskSendReady.OrderCode, equTaskSendReady.Width);
            return Json(rs);
        }
        /// <summary>
        /// 发送任务
        /// </summary>
        /// <param name="equ_TASKVM"></param>
        /// <returns></returns>
        [HttpPost, Route("Equ_SendTask")]
        public async Task<IActionResult> Equ_SendTask([FromBody] Equ_TaskSend equ_TASKVM)
        {
            var rs = await userService.Equ_SendTASK(equ_TASKVM.TaskNo, _mapper);

            return Json(rs);
        }
        /// <summary>
        /// 任务完成接收 5重做 3完成 4异常
        /// </summary>
        /// <param name="equ_TASKVM"></param>
        /// <returns></returns>
        [HttpPost, Route("Equ_ReceiveTask")]
        public async Task<IActionResult> Equ_ReceiveTask([FromBody] Equ_TaskReceive equ_TASKVM)
        {

            var rs = await userService.Equ_ReturnTask(equ_TASKVM, _mapper);
            return Json(rs);

        }
        /// <summary>
        /// 以工单批量 以完成的重新发送
        /// </summary>
        /// <param name="equ_TASKVM"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        [HttpPost, Route("Equ_ReceiveTaskOrder")]
        public async Task<IActionResult> Equ_ReceiveTaskOrder([FromBody] Equ_OrderReceive equ_TASKVM)
        {

            var rs = await userService.Equ_ReturnTaskOrder(equ_TASKVM);
            return Json(rs);

        }
        /// <summary>
        /// 自动工作跳转
        /// </summary>
        /// <param name="equ_TASKVM"></param>
        /// <returns></returns>
        [HttpPost, Route("Equ_TaskAutoWorkJump")]

        //[HttpPost, HttpGet, Route("login"), AllowAnonymous]
        [ObjectModelValidatorFilter(ValidatorModel.Login)]
        public async Task<IActionResult> Equ_TaskAutoWorkJump([FromBody] Equ_TaskAuto equ_TASKVM)
        {

            //   var calist=  _cache.Get<EQU_PLCConfig>("eQU_PLCConfigs");
            //IMemoryCache memoryCache =_cache. _context.GetService<IMemoryCache>();
            var rs = await userService.Equ_TaskAutoWorkJump(_mapper, equ_TASKVM);
            return Json(rs);

        }
        /// <summary>
        ///  自动工作跳转-多工单多任务 只允许192.168.110.1网段执行
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("Equ_TaskAutoWorkJumpMulti")]
        public async Task<IActionResult> Equ_TaskAutoWorkJumpMulti()
        {
            var rs = new WebResponseContent();
      
            rs = await userService.Equ_TaskAutoWorkJumpMulti(_mapper);
            if (rs.Status == false)
            {
                await _hubContext.Clients.All.SendAsync("ShowMsg", new MsgInfo { Title = ":", MsgContent = rs.Message });
            }
            return Json(rs);

        }
        /// <summary>
        ///  自动排产-多工单多 只允许192.168.110.1网段执行
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("Equ_TaskAutoPlanProductMulti")]


        public async Task<IActionResult> Equ_TaskAutoPlanProductMulti()
        {
            // --1需要排产的工单
            //select processing_machines, ProcessingMaterial,process_precision,*from PLAN_WORK_ORDER where IsProduction is null and isnull(processing_machines, '') = ''
            //and ProductionSeqNumber is null and ProcessingMaterial is not null and process_precision is not null;
            WebResponseContent rs = new WebResponseContent();
            EQU_FAULT_PHENOMENON eQU_FAULT_PHENOMENON = null;
            List<EQU_EQUIPMENT> equOrders = null;
            List<PLAN_WORK_ORDER>  planOrders = null;
            PLAN_WORK_ORDER planOrdersfirst = null;
            var isConnectUpdate1 = userService.IsIpConnect("192.168.1.160");
            if (isConnectUpdate1 == true)
            {
                rs.Message = $"192.168.1.160 不会执行！";
                rs.Status = false;
                return Json(rs);
            }
            planOrders = await _service.FindAsync<PLAN_WORK_ORDER>(t => t.IsProduction == null && t.processing_machines == ""
            && t.ProductionSeqNumber == null && t.ProcessingMaterial != "" && t.process_precision != ""&&t.process_type== "火花加工");
            //火花加工优先
            if (planOrders.Count == 0)
            {
                //如果没有火花加工的工单，则查找其他工单
                planOrders = await _service.FindAsync<PLAN_WORK_ORDER>(t => t.IsProduction == null && t.processing_machines == ""
                && t.ProductionSeqNumber == null && t.ProcessingMaterial != "" && t.process_precision != "");
               
            }
            planOrdersfirst = planOrders.FirstOrDefault();
            rs.Message = "1需要排产的工单" + Environment.NewLine;
            //换行
            if (planOrders.Count == 0)
            {
                rs.Message = "没有需要排产的工单";
                rs.Status = false;

                //eQU_FAULT_PHENOMENON = new EQU_FAULT_PHENOMENON();
                //eQU_FAULT_PHENOMENON.Content = rs.Message;
                //eQU_FAULT_PHENOMENON.FunctionType = "工单排产异常";
                //eQU_FAULT_PHENOMENON.CreateOn = DateTime.Now;
                //_service.DbContext.Add<EQU_FAULT_PHENOMENON>(eQU_FAULT_PHENOMENON);
                //_service.DbContext.SaveChanges();
                return Json(rs);
            }
            foreach (var item in planOrders)
            {
                rs.Message += item.OrderCode + " ";
            }
            //            --2.根据工单找出设备 ‌加工类型‌：‌精度‌：‌行程‌：‌材质‌：‌特性‌：刀柄，转速，重量
            //select EquipmentNo, Description, process_type, ProcessingMaterial, process_precision, CurrentOrder, *from EQU_EQUIPMENT where EquipmentNo is not null and CurrentOrder is null
            //and ProcessingMaterial like '%石墨%' and process_precision in ('0.015')
            var equEquNos = await _service.FindAsync<EQU_EQUIPMENT>(t => t.EquipmentNo != null);

            //火花加工优先
            equOrders = equEquNos.Where(t => t.EquipmentNo != null //string.IsNullOrEmpty(t.CurrentOrder) == true
               && t.process_type == planOrdersfirst.process_type
               ).ToList();
            if (equOrders.Count == 0)
            {
                equOrders = equEquNos.Where(t => t.EquipmentNo != null //string.IsNullOrEmpty(t.CurrentOrder) == true
                    && t.ProcessingMaterial.Contains(planOrdersfirst.ProcessingMaterial)
                    && t.process_precision == planOrdersfirst.process_precision
                    && t.HolderTypeId == planOrdersfirst.HolderType && planOrdersfirst.ProcessWeight < t.MaxLoadCapacity
                    && planOrdersfirst.length < t.itinerary_x && planOrdersfirst.width < t.itinerary_y && planOrdersfirst.height < t.itinerary_z
                    && t.RotationalSpeed == planOrdersfirst.RotationalSpeed
                    ).ToList();
            }
            rs.Message += "2.根据工单找出设备" + Environment.NewLine;
            if (equOrders.Count == 0)
            {
                rs.Message = "没有找到设备";
                rs.Status = false;
                eQU_FAULT_PHENOMENON = new EQU_FAULT_PHENOMENON();
                eQU_FAULT_PHENOMENON.Content = rs.Message;
                eQU_FAULT_PHENOMENON.FunctionType = "工单排产异常";
                eQU_FAULT_PHENOMENON.CreateOn = DateTime.Now;
                _service.DbContext.Add<EQU_FAULT_PHENOMENON>(eQU_FAULT_PHENOMENON);
                _service.DbContext.SaveChanges();
                return Json(rs);
            }
            foreach (var item in equOrders)
            {
                rs.Message += item.EquipmentNo + " ";
            }
            //            --3.给工单设置设备号
            //            update PLAN_WORK_ORDER set processing_machines = ''
            // where IsProduction is null and isnull(processing_machines, '') = ''
            //and ProductionSeqNumber is null and ProcessingMaterial is not null and process_precision is not null
            //var planOrdersUpdate = await _service.FindAsync<PLAN_WORK_ORDER>(t => t.IsProduction == null && t.processing_machines == ""
            //    && t.ProductionSeqNumber == null && t.ProcessingMaterial != "" && t.process_precision != "");
            rs.Message += "3.给工单设置设备号" + Environment.NewLine;
            int i = 0;
            var equ = equOrders.FirstOrDefault();
            if (planOrdersfirst != null)
            {
                var tools = _service.Find<EQU_TOOL>(t => t.Identifier == planOrdersfirst.OrderCode);
                //R角检查
                foreach (var item in tools)
                {
                    if (item.reality_R < 0)
                    {
                        rs.Message = $"实际半径{item.reality_R}不在范围内！";
                        rs.Status = false;
                        return Json(rs);
                    }
                    if (item.reality_R > equ.Max_reality_R)
                    {
                        rs.Message = $"实际半径{item.reality_R}不在范围内！";
                        rs.Status = false;
                        return Json(rs);
                    }
                }
                i++;
                planOrdersfirst.processing_machines = equ.Description;
                planOrdersfirst.IsProduction = "1";
                planOrdersfirst.ProductionSeqNumber = i;
                _service.DbContext.Update<PLAN_WORK_ORDER>(planOrdersfirst);
                _service.DbContext.SaveChanges();
                rs.Message += planOrdersfirst.OrderCode + " " + equ.Description + equ.Description;
            }
            rs.Status = true;
            return Json(rs);

        }
        ///// <summary>
        ///// 任务自动工作
        ///// </summary>
        ///// <param name="equ_TASKVM"></param>
        ///// <returns></returns>
        //[HttpPost, Route("Equ_TaskAutoWork")]
        //public async Task<IActionResult> Equ_TaskAutoWork([FromBody] Equ_TASKVM equ_TASKVM)
        //{
        //    var rs = await userService.Equ_TaskAutoWork(equ_TASKVM);
        //    return Json(rs);

        //}
        /// <summary>
        /// 工单激活
        /// </summary>
        /// <param name="equ_TASKVM"></param>
        /// <returns></returns>
        [HttpPost, Route("OrderActivation")]
        public async Task<IActionResult> OrderActivation([FromBody] Equ_TASKVM equ_TASKVM)
        {
            var rs = await userService.OrderActivation(equ_TASKVM);
            return Json(rs);

        }

        //public async Task<WebResponseContent> Equ_TASK(Equ_TASKVM equ_TASKVM)
        //{
        //    string msg = string.Empty;
        //    try
        //    {
        //        Sys_User user = await repository.FindAsIQueryable(x => x.UserName == loginInfo.UserName)
        //            .FirstOrDefaultAsync();

        //        if (user == null || loginInfo.Password.Trim().EncryptDES(AppSetting.Secret.User) != (user.UserPwd ?? ""))
        //            return webResponse.Error(ResponseType.LoginError);

        //        string token = JwtHelper.IssueJwt(new UserInfo()
        //        {
        //            User_Id = user.User_Id,
        //            UserName = user.UserName,
        //            Role_Id = user.Role_Id
        //        });
        //        user.Token = token;
        //        webResponse.Data = new { token, userName = user.UserTrueName, img = user.HeadImageUrl };
        //        repository.Update(user, x => x.Token, true);
        //        UserContext.Current.LogOut(user.User_Id);

        //        loginInfo.Password = string.Empty;

        //        return webResponse.OK(ResponseType.LoginSuccess);
        //    }
        //    catch (Exception ex)
        //    {
        //        msg = ex.Message + ex.StackTrace;
        //        if (_context.GetService<Microsoft.AspNetCore.Hosting.IWebHostEnvironment>().IsDevelopment())
        //        {
        //            throw new Exception(ex.Message + ex.StackTrace);
        //        }
        //        return webResponse.Error(ResponseType.ServerError);
        //    }
        //    finally
        //    {
        //        Logger.Info(LoggerType.Login, loginInfo.Serialize(), webResponse.Message, msg);
        //    }
        //}

        #endregion

        #region 刀具
        /// <summary>
        /// 刀具
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpGet, Route("/api/ToDo/GetAll")]
        public async Task<ApiResponse> GetAll([FromQuery] ToDoParameter param)
        {
            return await userService.GetAllAsync(param, _mapper);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpGet, Route("/api/ToDo/GetINTE_SHELVES")]
        public async Task<ApiResponse> GetINTE_SHELVES([FromQuery] ToDoParameter param)
        {
            return await userService.GetINTE_SHELVES(param, _mapper);
        }
        /// <summary>
        /// Get
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpGet, Route("/api/ToDo/Get")]
        public async Task<ApiResponse> GetAsync(string Id)
        {
            return await userService.GetAsync(Id);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpGet, Route("/api/ToDo/FirstTool")]
        public async Task<ApiResponse> FirstTool([FromQuery] ToDoParameter param)
        {
            return await userService.FirstTool(param, _mapper);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="toDoDto"></param>
        /// <returns></returns>
        [HttpPost, Route("/api/ToDo/Update")]
        public async Task<ApiResponse> UpdateAsync([FromBody] ToDoDto model)
        {


            //      return new ApiResponse(true, toDoDtos);
            return await userService.UpdateAsync(model, _mapper);
        }
        /// <summary>
        /// Task<ApiResponse> Add([FromBody] ToDoDto model)
        /// </summary>
        /// <param name="toDoDto"></param>
        /// <returns></returns>
        [HttpPost, Route("/api/ToDo/Add")]
        public async Task<ApiResponse> AddAsync([FromBody] ToDoDto model)
        {
            return await userService.AddAsync(model, _mapper);
        }
        [HttpDelete, Route("/api/ToDo/Delete")]
        public async Task<ApiResponse> DeleteAsync(string Id)
        {
            return await userService.DeleteAsync(Id);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpGet, Route("/api/ToDo/Summary")]
        public async Task<ApiResponse> Summary()
        {
            return await userService.Summary(_mapper);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="equ_TASKVM"></param>
        /// <returns></returns>
        [HttpGet, Route("/api/ToDo/Test")]
        public ApiResponse Test(Equ_TASKVM equ_TASKVM)
        {
            ToDoDto toDoDto = new ToDoDto();
            toDoDto.Identifier = "123";
            var k = userService.UpdateAsync(toDoDto, _mapper);
            // 创建对象映射工具

            EQU_TOOL eQU_TOOL = new EQU_TOOL();
            eQU_TOOL.Identifier = "123";
            // ToDoDto toDoDto = new ToDoDto();
            var toDoDtos = _mapper.Map<ToDoDto>(eQU_TOOL);

            return new ApiResponse(true, toDoDtos);

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="loginInfo"></param>
        /// <returns></returns>
        [HttpPost, Route("/api/Login/Login"), AllowAnonymous]
        //  [HttpPost, HttpGet, Route("login"), AllowAnonymous]
        [ObjectModelValidatorFilter(ValidatorModel.LoginOnlyPassWord)]
        public async Task<ApiResponse> Login([FromBody] LoginInfo loginInfo)
        {
            var rs1 = await Service.Login(loginInfo);
            //   var rs=await userService.Login(loginInfo);
            return new ApiResponse(rs1.Message, rs1.Status);
        }

        #endregion
        #region  任务
        [HttpGet, Route("/api/Task/GetTaskAll")]
        public async Task<ApiResponse> GetTaskAll([FromQuery] ToDoParameter param) => await userService.GetAllTaskAsync(param, _mapper);

        #endregion

        #region PLC
        /// <summary>
        /// PLC当前值 （对刀仪)
        /// </summary>
        /// <param name="taskOptions"></param>
        /// <returns></returns>
        [Route("PlcGet"), HttpPost]
        public async Task<object> PlcGet([FromBody] EQU_PLCConfig taskOptions)
        {
            return await Service.PlcGet(taskOptions);
        }
        /// <summary>
        /// PLC当前值 （对刀仪) Auto
        /// </summary>
        /// <param name="taskOptions"></param>
        /// <returns></returns>
        [Route("PlcGetAuto"), HttpPost]
        public async Task<object> PlcGetAuto()
        {
            return await Service.PlcGetAuto();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="equ_TASKVM"></param>
        /// <returns></returns>
        [HttpPost, Route("Equ_PLC")]
        public async Task<IActionResult> Equ_PLC([FromBody] Equ_TASKVM equ_TASKVM)
        {
            List<PLCData> pLCDatas = new List<PLCData>();
            //var isOpen = PlcHelper.Instance.OpenPlc(CpuType.S71500, 0, 1);
            //if (isOpen)   //判断是否成功
            //{
            //    var db1RoBotArm = PlcHelper.Instance.ReadReal(273, 8);
            //    var db1CarArm = PlcHelper.Instance.ReadReal(273, 12);
            //    var db1BigCarArm = PlcHelper.Instance.ReadReal(273, 16);
            //}
            var rs = userService.GetPLCData(_mapper);

            // PlcHelper.Instance.ClosePlc(PlcHelper.Instance.Plc);


            //3.发送MQ
            //  MQHelper.MQSendMsg(rs.Data.ToString(), MQqueue.Equ_SendTask.ToString());
            // List<string> mes =new List<string>();
            // MQHelper.MQReceived(out mes, "Equ");

            return Json(pLCDatas);
        }
        #endregion

        #region log
        [Route("sendlog"), HttpPost]
        [ActionPermission(ActionPermissionOptions.Update)]
        public async Task<object> Sendlog([FromBody] Equ_TaskReceive taskOptions)
        {
            return await Service.Sendlog(taskOptions);
        }

        [Route("Faultlog"), HttpPost]
        [ActionPermission(ActionPermissionOptions.Update)]
        public async Task<object> Faultlog([FromBody] Equ_TaskReceive taskOptions)
        {
            return await Service.Faultlog(taskOptions);
        }
        [Route("EarlyWarning"), HttpPost]
        // [ActionPermission(ActionPermissionOptions.Update)]
        public async Task<object> EarlyWarning([FromBody] EQU_COM_DEFINITION_TASK_DETECTION taskOptions)
        {
            var rs = new WebResponseContent();
            List<dynamic> pw = new List<dynamic>();
            var pfirst = await _service.FindAsyncFirst<PLAN_WORK_ORDER>(t => t.OrderCode == taskOptions.OrderCode);
            var equfirst = await _service.FindAsyncFirst<EQU_EQUIPMENT>(t => t.Description == pfirst.processing_machines);
            var equs = await _service.FindAsync<EQU_EQUIPMENT>(t => t.EquipmentCode== "SLK_001"||t.EquipmentCode== "JCR_001"||t.EquipmentCode== "JZC_001");
            
            pw.Add(new  { processingNumber=pfirst.ProcessingNumber, ProcessingTime =pfirst.ProcessingTime, ExecuteOrderTime = CalculatePercentage(pfirst.UsedToolCount == null ? 0 : pfirst.UsedToolCount.Value, pfirst.UsedToolTotal == null ? 0 : pfirst.UsedToolTotal.Value), Img = "http://192.168.110.183:8088/" + equfirst.Img, EquipmentCode="", IsException=false,IsEnableStr = "", IsOnlineStr= equfirst.IsOnline == false ? "<span style='color:red'>未在线</span>" : "<span style='color:green'>在线</span>", accuracy = pfirst.accuracy, OrderCode = pfirst.OrderCode, UsedToolTotal = pfirst.UsedToolTotal, processing_machines = pfirst.processing_machines });
            foreach (var item in equs)
            {
                pw.Add(new  { processingNumber=0,ProcessingTime = 0, ExecuteOrderTime =0, Img = "http://192.168.110.183:8088/"+item.Img, EquipmentCode = item.EquipmentCode, IsException = item.IsException, IsEnableStr = item.IsEnable == false ? "<span style='color:red'>未就绪</span>" : "<span style='color:green'>已就绪</span>", IsOnlineStr = item.IsOnline == false ? "<span style='color:red'>未在线</span>" : "<span style='color:green'>在线</span>", accuracy = 0, OrderCode = pfirst.OrderCode, UsedToolTotal = 0, processing_machines =item.EquipmentNameZH });
            }
            
            rs.Data = pw;
            rs.Message = $"192.168.1.160 不通 不会执行！";
            rs.Status = false;
            return Json(rs);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="numerator"></param>
        /// <param name="denominator"></param>
        /// <returns></returns>
        private decimal CalculatePercentage(int numerator, int denominator)
        {
            if (denominator == 0 ||  (numerator)==0)
            {
                return 0;
            }
            return Math.Round((Convert.ToDecimal (numerator )/ denominator * 100),2);
        }
        #endregion
        /// <summary>
        /// 再次执行任务
        /// </summary>
        /// <param name="equ_TASKVM"></param>
        /// <returns></returns>
        [HttpPost, Route("taskExecuteAgain")]
        public async Task<IActionResult> TaskExecuteAgain([FromBody] Equ_TaskReceive equ_TASKVM)
        {

            var rs = await userService.TaskExecuteAgain(equ_TASKVM, _mapper);
            return Json(rs);

        }
        /// <summary>
        /// 找正记录数据
        /// </summary>
        /// <param name="equ_TASKVM"></param>
        /// <returns></returns>
        [HttpPost, Route("PlcAlignRecordTask")]
        public async Task<IActionResult> PlcAlignRecordTask([FromBody] PlcAlignRecordTask equ_TASKVM)
        {

            var rs = await userService.PlcAlignRecordTask(equ_TASKVM);
            return Json(rs);

        }

        //Plcequ
        /// <summary>
        /// PLC设备数据
        /// </summary>
        /// <param name="equ_TASKVM"></param>
        /// <returns></returns>
        [HttpPost, Route("Plcequ")]
        public async Task<IActionResult> Plcequ([FromBody] Plcequ equ_TASKVM)
        {

            var rs = await userService.Plcequ(equ_TASKVM);
            return Json(rs);

        }
        /// <summary>
        /// 检测仪启动
        /// </summary>
        /// <param name="equ_TASKVM"></param>
        /// <returns></returns>
        [HttpPost, Route("PlcStart")]
        public async Task<IActionResult> PlcStart([FromBody] EQU_TOOL equ_TASKVM)
        {
            var rs = await userService.PlcStart(equ_TASKVM);
            return Json(rs);
        }//multi
        /// <summary>
        /// 检测仪启动 多次 只允许192.168.1.3
        /// </summary>
        /// <param name="equ_TASKVM"></param>
        /// <returns></returns>
        [HttpPost, Route("PlcStartMulti")]
        public async Task<IActionResult> PlcStartMulti()
        {

            var rs = await userService.PlcStartMulti(_hubContext);
            if (rs.Status == false)
            {
                await _hubContext.Clients.All.SendAsync("ShowMsg1", new MsgInfo { Title = ":", MsgContent = rs.Message });
           
            }
            return Json(rs);
        }
        /// <summary>
        /// 退库（退出整刀）
        /// </summary>
        /// <param name="equ_TASKVM"></param>
        /// <returns></returns>
        [HttpPost, Route("PlcOutStock")]
        public async Task<IActionResult> PlcOutStock([FromBody] EQU_TOOL equ_TASKVM)
        {

            var rs = await userService.PlcOutStock(equ_TASKVM);
            return Json(rs);

        }
        /// <summary>
        /// 入库（整刀）
        /// </summary>
        /// <param name="equ_TASKVM"></param>
        /// <returns></returns>
        [HttpPost, Route("PlcInStock")]
        public async Task<IActionResult> PlcInStock([FromBody] EQU_TOOL equ_TASKVM)
        {
            var rs = await userService.PlcInStock(equ_TASKVM);
            return Json(rs);
        }
        /// <summary>
        /// 装刀看板
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("PlcVeiwPlan")]
        public async Task<IActionResult> PlcVeiwPlan()
        {
            var rs = await userService.PlcVeiwPlan(_cache);
            
            return Json(rs);
        }
        /// <summary>
        /// PlcRestart
        /// </summary>
        /// <param name="eQU_TOOL"></param>
        /// <returns></returns>
        [HttpPost, Route("PlcRestart")]
        public async Task<IActionResult> PlcRestart()
        {
            var rs = await userService.PlcRestart();
            return Json(rs);
        }
        /// <summary>
        /// Auto装刀看板PLC
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("PlcVeiwPlanAuto")]
        public async Task<IActionResult> PlcVeiwPlanAuto()
        {
            var rs = await userService.PlcVeiwPlanAuto();
            return Json(rs);
        }
        /// <summary>
        /// 设备是否在线 只允许192.168.1.1网段执行
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("EquIsPing")]
        public async Task<IActionResult> EquIsPing()
        {
            var rs = new WebResponseContent();
            var isConnectUpdate1 = userService.IsIpConnect("192.168.1.160");
            if (isConnectUpdate1 == false)
            {
                rs.Message = $"192.168.1.160 不通 不会执行！";
                rs.Status = false;
                return Json(rs);
            }
            rs = await userService.EquIsPing();
            return Json(rs);
        }
        /// <summary>
        /// 短信发送
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("FaultMessage")]
        public async Task<IActionResult> FaultMessage()
        {
            string rs = string.Empty;
            EQU_FAULT_PHENOMENON eQU_FAULT_PHENOMENON = _service.Find<EQU_FAULT_PHENOMENON>(t => t.Content != "" && t.IsSend == "1").FirstOrDefault();
            if (eQU_FAULT_PHENOMENON == null)
            {
                rs = "没有待发信息";
                return Json(rs);
            }
            var accessKeyId = userService.QueryInteConfigure("AccessKeyId");
            if (accessKeyId == null)
            {
                rs = "未配置AccessKeyId";
                return Json(rs);
            }

            var accessKeySecret = userService.QueryInteConfigure("AccessKeySecret");
            if (accessKeySecret == null)
            {
                rs = "未配置AccessKeySecret";
                return Json(rs);
            }

            AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config
            {
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
                AccessKeyId = accessKeyId.ConfigureParam,// "LTAI5tECNMuKjWJk7Hok5sBd",//Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                AccessKeySecret = accessKeySecret.ConfigureParam// "e6ksCLysBvv830SIPJH4p5wBgsoOJu"// Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
            };
            // 配置 Endpoint
            config.Endpoint = "dysmsapi.aliyuncs.com";
            AlibabaCloud.SDK.Dysmsapi20170525.Client client = new AlibabaCloud.SDK.Dysmsapi20170525.Client(config);

            List<string> phones = null;
            var equsTaskLock = userService.QueryInteConfigure("FaultMessage");
            if (equsTaskLock == null)
            {
                rs = "未配置手机";
                return Json(rs);
            }
            {
                phones = equsTaskLock.ConfigureParam.Split(",").ToList();
            }
            eQU_FAULT_PHENOMENON.IsSend = "0";
            eQU_FAULT_PHENOMENON.SendOn = DateTime.Now;
            eQU_FAULT_PHENOMENON.SendPhone = string.Join(",", phones);// phones.ToJson(",").ToString(); ;
            foreach (var item in phones)
            {

                // 创建请求对象并设置入参
                AlibabaCloud.SDK.Dysmsapi20170525.Models.SendSmsRequest sendSmsRequest = new AlibabaCloud.SDK.Dysmsapi20170525.Models.SendSmsRequest
                {

                    SignName = "MES消息",//"阿里云短信测试",
                    TemplateCode = "SMS_476765018",//"SMS_154950909",
                    PhoneNumbers = item,
                    TemplateParam = "{\"name\":\"" + item + "\",\"store\":\"" + eQU_FAULT_PHENOMENON.TaskNo + "\"}",
                };
                // 复制代码运行请自行打印 API 的返回值
                AlibabaCloud.SDK.Dysmsapi20170525.Models.SendSmsResponse resp = client.SendSms(sendSmsRequest);
                if (resp.Body.Code == "OK")
                {
                    rs = "发送成功";
                }
                else
                {
                    rs = "发送失败";
                }
                //    Console.WriteLine(AlibabaCloud.TeaUtil.Common.ToJSONString(resp));

            }
            _service.DbContext.Set<EQU_FAULT_PHENOMENON>().Update(eQU_FAULT_PHENOMENON);
            _service.DbContext.SaveChanges();
            //////批量 不支持
            //AlibabaCloud.SDK.Dysmsapi20170525.Models.SendBatchSmsRequest sendBatchSmsRequest = new AlibabaCloud.SDK.Dysmsapi20170525.Models.SendBatchSmsRequest()
            //{
            //    SignNameJson = "[\"MES消息\"]",//"[\"MES消息\"]",["阿里云","阿里巴巴"]
            //    TemplateCode = "SMS_476765018",
            //    PhoneNumberJson = "[\"13549201181\"]",
            //    TemplateParamJson = "[{\"name\":\"13549201181\"}]"// "[{\"name\":\"13549201181\",\"store\":\"" + eQU_FAULT_PHENOMENON.Content + "\"}]"//@$"[{ "name":"TemplateParamJson"},{"name":"TemplateParamJson"}]"

            //};
            //AlibabaCloud.SDK.Dysmsapi20170525.Models.SendBatchSmsResponse resp1 = client.SendBatchSms(sendBatchSmsRequest);
            //if (resp1.Body.Code == "OK")
            //{
            //    rs = "发送成功";
            //}
            //else
            //{
            //    rs = "发送失败";
            //}
            return Json(rs);
        }

        #region select
        /// <summary>
        /// select 程序
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("SelectPrograme")]
        public async Task<IActionResult> SelectPrograme([FromBody] PLAN_WORK_ORDER pLAN)
        {
            List<Select> source = new List<Select>();
            var li = _service.Find<PROC_PROGRAM>(t => t.Identifier == pLAN.OrderCode).ToList();
            foreach (var item in li)
            {
                source.Add(new Select { key = item.Id.ToString().ToUpper(), value = item.program_name + "(" + item.sequence + "|" + item.Identifier + ")", sort = item.sequence.ToString() });
            }
            return Json(source);
        }
        /// <summary>
        /// select 刀
        /// </summary>
        /// <param name="pLAN"></param>
        /// <returns></returns>
        [HttpPost, Route("SelectTool")]
        public async Task<IActionResult> SelectTool([FromBody] PLAN_WORK_ORDER pLAN)
        {
            List<Select> source = new List<Select>();
            var li = _service.Find<EQU_TOOL>(t => t.Identifier == pLAN.OrderCode).ToList();
            foreach (var item in li)
            {
                source.Add(new Select { key = item.Id.ToString().ToUpper(), value = item.tool_name + "(" + item.program_seq + "|" + item.Identifier + ")", sort = item.program_seq.ToString() });
            }
            return Json(source);
        }

        #endregion


        #region by guoyuguo 2024.12.30  中央刀库

        /// <summary>
        /// 中央刀库  192.168.1.3执行
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("LoadToolSate")]
        public async Task<IActionResult> LoadToolSate()
        {
            var rs = new WebResponseContent();
            var isConnectUpdate1 = userService.IsIpConnect("192.168.1.3");
            if (isConnectUpdate1 == false)
            {
                rs.Message = $"192.168.1.3 不会执行！";
                rs.Status = false;
                return Json(rs);
            }
            rs = await userService.LoadToolSate();
            return Json(rs);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="input"></param>
        /// <param name="index"></param>
        /// <param name="separator"></param>
        /// <returns></returns>
        private string SplitEx(string input, int index = 0, string separator = "-")
        {
            return input.Split(separator)[index].ToString();
        }
        /// <summary>
        /// 工件写入RFID
        /// </summary>
        /// <param name="Order_Id"></param>
        /// <returns></returns>
        [HttpPost, Route("PlcWorkpieceRFID")]
        public async Task<IActionResult> PlcWorkpieceRFID([FromBody] PlcWorkpieceRFID pLAN_WORK)
        {
            var rs = await userService.PlcWorkpieceRFID(pLAN_WORK);
            var plan_work_order = await _service.FindAsyncFirst<PLAN_WORK_ORDER>(t => t.Order_Id ==Guid.Parse( pLAN_WORK.Order_Id));
            var pROC_MATERIAL  = await _service.FindAsyncFirst<PROC_MATERIAL>(t => t.Id ==Guid.Parse( pLAN_WORK.Id));
            string coderfid = "126";
            int indexSplit = 3;

            coderfid = DateTime.Now.ToString("yy") + SplitEx(plan_work_order.OrderCode, indexSplit);//调度id

            //      procMaterilFirst.RfidCode = SplitEx(plan_work_order.OrderCode, indexSplit);//调度id

            WebResponseContent rs1 = new WebResponseContent();
            R2KReader objreader = new R2KReader();
            RfidMessage rfidMessage = new RfidMessage();
            string Port = "502";
            string IpAddress = "192.168.1.160";
            try
            {

                string data = "EA AB 34 00 00 00 00 7E 00 00 00 7E 00 00 00 01";
                string hexString = Convert.ToString(Convert.ToInt32(coderfid), 16);
                string hexStringCNC = Convert.ToString(Convert.ToInt32(pROC_MATERIAL.machine), 16);
                // 因为最后一个部分后面没有空格，所以最后一个元素会被截断。我们可以手动添加
                // 分割字符串

                string outStr = string.Empty;
                string outStrLast = string.Empty;
                rfidMessage.button_Disconnect_TCP_Click(objreader);
                //读取标签内存
                rfidMessage.button_Connect_TCP_Click(objreader, Port.ToString(), IpAddress);
                //  rfidMessage.button_accessExec_Click(objreader, "A1 29 34 00");

                //string ReaderModelText = objreader.ProductModel_str;//显示产品型号
                //string ReaderSNText = objreader.ProductSN_str;      //显示产品序列号
                //string ReaderFirmwareText = objreader.FirmwareVersion_str;//显示固件版本

                rfidMessage.ReadRFID(objreader, out outStr, "EPC区");
                rfidMessage.button_Disconnect_TCP_Click(objreader);
                data = outStr;
                if (outStr == "")
                {
                    rs1.Status = false;
                    rs1.Message = "没有读取到标签";
                    return Json(rs1);
                }
                string[] parts = data.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries); // 使用空格分割并移除空项
                string originalString = string.Join(" ", parts); // 重新组合成一个字符串
                string replacement = hexString.PadLeft(8, '0').ToUpper();  // 替换的字符串
                string replacementCNC = hexStringCNC.PadLeft(8, '0').ToUpper();  // 替换的字符串

                string strRfid = FormatHexString(replacement);
                string strCNC = FormatHexString(replacementCNC);
               
                int startIndex = 0; // 起始索引（注意：基于0开始）
                int length = 11; // 需要替换的长度
                // 删除原有的部分并插入新的字符串
                string newString = originalString.Remove(startIndex, length + 1);

                string newString2 = newString.Remove(startIndex, length + 1);
                // string newString1 = "EA AB 34 00 00 00 00 7E 00 00 00 7E 00 00 00 01";// newString.Insert(startIndex, replacement);
                
             //   string newString1 = newString.Insert(startIndex, "" + str + " ");

                string newString2input = newString2.Insert(startIndex, "" + strCNC + " ");
                string newString3input = newString2input.Insert(startIndex, "" + strRfid + " ");
                //写入标签内存
                rfidMessage.button_Connect_TCP_Click(objreader, Port.ToString(), IpAddress);
                rfidMessage.button_accessExec_Click(objreader, newString3input);

                rfidMessage.button_Disconnect_TCP_Click(objreader);

                //读取标签内存
                rfidMessage.button_Connect_TCP_Click(objreader, Port.ToString(), IpAddress);


                rfidMessage.ReadRFID(objreader, out outStrLast, "EPC区");


                rfidMessage.button_Disconnect_TCP_Click(objreader);

                var workrfidstr = Format16to10String(replacement);//转换成10进制  工件RFID
                var cndstr=Format16to10String(replacementCNC);
                if (outStrLast == newString3input&&rs.Status==true)
                {
                    rs1.Status = true;
                    rs1.Message = $"写入成功【rfid:{workrfidstr}/cnc:{cndstr}】";
                    rs1.Data = outStrLast;

                }
                else
                {
                    rs1.Status = false;
                    rs1.Message = "写入失败";
                    rs1.Data = outStrLast;

                }

            }
            catch (Exception ex)
            {
                Console.WriteLine("An error occurred: " + ex.Message);
            }
            finally
            {
                rfidMessage.button_Disconnect_TCP_Click(objreader);
            }

            return Json(rs1);
        }
        /// <summary>
        /// 16进制转10进制
        /// </summary>
        /// <param name="hexString"></param>
        /// <returns></returns>
        private string Format16to10String(string hexString)
        {
     
             BigInteger decimalValue = BigInteger.Parse(hexString, NumberStyles.HexNumber); // 使用BigInteger以处理超大数情况
      
            return decimalValue.ToString();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="pLAN_WORK"></param>
        /// <returns></returns>
        [HttpPost, Route("PlcToolRFIDNoSend")]
        public async Task<IActionResult> PlcToolRFIDNoSend([FromBody] PlcToolRFID pLAN_WORK)
        {

            //  var plan_work_order = await _service.FindAsyncFirst<PLAN_WORK_ORDER>(t => t.Order_Id == Guid.Parse(pLAN_WORK.Order_Id));
            string coderfid = "126";
            int indexSplit = 3;

            coderfid = DateTime.Now.ToString("yy") + SplitEx(pLAN_WORK.Identifier, 2) + $"{pLAN_WORK.program_seq}";//调度id// DateTime.Now.ToString("yy") + SplitEx(plan_work_order.OrderCode, indexSplit);//调度id

            //      procMaterilFirst.RfidCode = SplitEx(plan_work_order.OrderCode, indexSplit);//调度id
            WebResponseContent rs = new WebResponseContent();
            WebResponseContent rs1 = new WebResponseContent();
            R2KReader objreader = new R2KReader();
            RfidMessage rfidMessage = new RfidMessage();
            string Port = "502";
            string IpAddress = "192.168.1.160";
            try
            {

                string data = "EA AB 34 00 00 00 00 7E 00 00 00 7E 00 00 00 01";
                string hexString = Convert.ToString(Convert.ToInt32(coderfid), 16);
                // 因为最后一个部分后面没有空格，所以最后一个元素会被截断。我们可以手动添加
                // 分割字符串

                string outStr = string.Empty;
                string outStrLast = string.Empty;
                rfidMessage.button_Disconnect_TCP_Click(objreader);
                Thread.Sleep(200);
                //读取标签内存
                rfidMessage.button_Connect_TCP_Click(objreader, Port.ToString(), IpAddress);
                Thread.Sleep(200);
                rfidMessage.ReadRFID(objreader, out outStr, "EPC区");
                Thread.Sleep(200);
                rfidMessage.button_Disconnect_TCP_Click(objreader);
                if (outStr == "")
                {
                    rs1.Status = false;
                    rs1.Message = "没有读取到标签";
                    return Json(rs1);
                }


                data = outStr;
                string[] parts = data.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries); // 使用空格分割并移除空项
                string originalString = string.Join(" ", parts); // 重新组合成一个字符串
                string replacement = hexString.PadLeft(8, '0').ToUpper(); ; // 替换的字符串

                string str = FormatHexString(replacement);

                int startIndex = 0; // 起始索引（注意：基于0开始）
                int length = 11; // 需要替换的长度

                // 删除原有的部分并插入新的字符串
                string newString = originalString.Remove(startIndex, length + 1);

                // string newString1 = "EA AB 34 00 00 00 00 7E 00 00 00 7E 00 00 00 01";// newString.Insert(startIndex, replacement);
                string newString1 = newString.Insert(startIndex, "" + str + " ");


                //写入标签内存

                Thread.Sleep(200);
                rfidMessage.button_Connect_TCP_Click(objreader, Port.ToString(), IpAddress);
                Thread.Sleep(200);
                rfidMessage.button_accessExec_Click(objreader, newString1);
                Thread.Sleep(200);
                rfidMessage.button_Disconnect_TCP_Click(objreader);
                Thread.Sleep(200);
                //读取标签内存
                rfidMessage.button_Connect_TCP_Click(objreader, Port.ToString(), IpAddress);
                Thread.Sleep(200);

                rfidMessage.ReadRFID(objreader, out outStrLast, "EPC区");
                Thread.Sleep(200);

                rfidMessage.button_Disconnect_TCP_Click(objreader);

                if (outStrLast == newString1)
                {
                    rs = await userService.PlcToolRFIDNoSend(pLAN_WORK);
                    var eQU_TOOLMeasure = await _service.FindAsyncFirst<EQU_TOOL_Measure>(t => t.tool_name != null);
                    var eQU_TOOL = await _service.FindAsyncFirst<EQU_TOOL>(t => t.Identifier == pLAN_WORK.Identifier && t.program_seq == pLAN_WORK.program_seq);
                    if (eQU_TOOLMeasure != null && eQU_TOOLMeasure.RfidCode == eQU_TOOL.RfidCode && eQU_TOOL != null)
                    {
                    }
                    else
                    {
                        rs = await userService.PlcToolRFIDNoSend(pLAN_WORK);
                    }
                    if (rs != null && rs.Status == true)
                    {
                        rs1.Status = true;
                        rs1.Message = "写入成功";
                        rs1.Data = outStrLast;
                        rs.Status = true;
                        rs.Message = "写入成功";
                    }
                    else
                    {
                        rs1.Status = false;
                        rs1.Message = "写入失败";
                        rs1.Data = outStrLast;
                        rs.Status = false;
                        rs.Message = "写入失败";
                    }


                }
                else
                {

                    rs1.Status = false;
                    rs1.Message = "写入失败";
                    rs1.Data = outStrLast;
                    rs.Status = false;
                    rs.Message = "写入失败";


                }
                return Json(rs1);
            }
            catch (Exception ex)
            {
                Console.WriteLine("An error occurred: " + ex.Message);
            }
            finally
            {
                //   rfidMessage.button_Disconnect_TCP_Click(objreader);
            }

            return Json(rs1);
        }

        /// <summary>
        /// 刀具写入RFID
        /// </summary>
        /// <param name="pLAN_WORK"></param>
        /// <returns></returns>
        [HttpPost, Route("PlcToolRFID")]
        public async Task<IActionResult> PlcToolRFID([FromBody] PlcToolRFID pLAN_WORK)
        {
            
          //  var plan_work_order = await _service.FindAsyncFirst<PLAN_WORK_ORDER>(t => t.Order_Id == Guid.Parse(pLAN_WORK.Order_Id));
            string coderfid = "126";
            int indexSplit = 3;

            coderfid = DateTime.Now.ToString("yy") + SplitEx(pLAN_WORK.Identifier, 2) + $"{pLAN_WORK.program_seq}";//调度id// DateTime.Now.ToString("yy") + SplitEx(plan_work_order.OrderCode, indexSplit);//调度id

            //      procMaterilFirst.RfidCode = SplitEx(plan_work_order.OrderCode, indexSplit);//调度id
            WebResponseContent rs = new WebResponseContent();
            WebResponseContent rs1 = new WebResponseContent();
            R2KReader objreader = new R2KReader();
            RfidMessage rfidMessage = new RfidMessage();
            string Port = "502";
            string IpAddress = "192.168.1.160";
            /*
            try
            {

                string data = "EA AB 34 00 00 00 00 7E 00 00 00 7E 00 00 00 01";
                string hexString = Convert.ToString(Convert.ToInt32(coderfid), 16);
                // 因为最后一个部分后面没有空格，所以最后一个元素会被截断。我们可以手动添加
                // 分割字符串

                string outStr = string.Empty;
                string outStrLast = string.Empty;
                rfidMessage.button_Disconnect_TCP_Click(objreader);
                Thread.Sleep(200);
                //读取标签内存
                rfidMessage.button_Connect_TCP_Click(objreader, Port.ToString(), IpAddress);
                Thread.Sleep(200);
                rfidMessage.ReadRFID(objreader, out outStr, "EPC区");
                Thread.Sleep(200);
                rfidMessage.button_Disconnect_TCP_Click(objreader);
                if(outStr=="")
                    {
                    rs1.Status = false;
                    rs1.Message = "没有读取到标签";
                    return Json(rs1);
                }
                   
                   
                data = outStr;
                string[] parts = data.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries); // 使用空格分割并移除空项
                string originalString = string.Join(" ", parts); // 重新组合成一个字符串
                string replacement = hexString.PadLeft(8, '0').ToUpper(); ; // 替换的字符串

                string str = FormatHexString(replacement);

                int startIndex = 0; // 起始索引（注意：基于0开始）
                int length = 11; // 需要替换的长度

                // 删除原有的部分并插入新的字符串
                string newString = originalString.Remove(startIndex, length + 1);

                // string newString1 = "EA AB 34 00 00 00 00 7E 00 00 00 7E 00 00 00 01";// newString.Insert(startIndex, replacement);
                string newString1 = newString.Insert(startIndex, "" + str + " ");


                //写入标签内存

                Thread.Sleep(200);
                rfidMessage.button_Connect_TCP_Click(objreader, Port.ToString(), IpAddress);
                Thread.Sleep(200);
                rfidMessage.button_accessExec_Click(objreader, newString1);
                Thread.Sleep(200);
                rfidMessage.button_Disconnect_TCP_Click(objreader);
                Thread.Sleep(200);
                //读取标签内存
                rfidMessage.button_Connect_TCP_Click(objreader, Port.ToString(), IpAddress);
                Thread.Sleep(200);

                rfidMessage.ReadRFID(objreader, out outStrLast, "EPC区");
                Thread.Sleep(200);

                rfidMessage.button_Disconnect_TCP_Click(objreader);

                if (outStrLast == newString1)
                {
                    rs = await userService.PlcToolRFID(pLAN_WORK);
                    var li190 = await _service.FindAsync<EQU_PLCConfig>(t => (t.PlcNameZH == "对刀仪准备启动BT40" || t.PlcNameZH == "对刀仪准备启动A63") && t.DbBlockType == "Send");
                    var eQU_TOOLMeasure = await _service.FindAsyncFirst<EQU_TOOL_Measure>(t => t.tool_name != null);
                    var eQU_TOOL = await _service.FindAsyncFirst<EQU_TOOL>(t => t.Identifier == pLAN_WORK.Identifier && t.program_seq == pLAN_WORK.program_seq);
                  if(eQU_TOOLMeasure!=null&&eQU_TOOLMeasure.RfidCode== eQU_TOOL.RfidCode&& eQU_TOOL!=null)
                    {
                       // userService.SetToolPlcPaly(eQU_TOOL, li190);
                    }
                    else
                    {
                        rs = await userService.PlcToolRFID(pLAN_WORK);
                    }
                    var eQU_TOOL2 = await _service.FindAsyncFirst<EQU_TOOL>(t => t.Identifier == pLAN_WORK.Identifier && t.program_seq == pLAN_WORK.program_seq);
                    if (rs != null && rs.Status == true&& eQU_TOOLMeasure != null && eQU_TOOLMeasure.RfidCode == eQU_TOOL2.RfidCode && eQU_TOOL != null)
                    {
                        userService.SetToolPlcPaly(eQU_TOOL2, li190);
                        rs1.Status = true;
                        rs1.Message = "写入成功";
                        rs1.Data = outStrLast;
                        rs.Status = true;
                        rs.Message = "写入成功";
                    }
                    else
                    {
                        rs1.Status = false;
                        rs1.Message = "写入失败";
                        rs1.Data = outStrLast;
                        rs.Status = false;
                        rs.Message = "写入失败";
                    }
                  

                }
                else
                {

                    rs1.Status = false;
                    rs1.Message = "写入失败";
                    rs1.Data = outStrLast;
                    rs.Status = false;
                    rs.Message = "写入失败";
                   

                }
                return Json(rs1);
            }
            catch (Exception ex)
            {
                Console.WriteLine("An error occurred: " + ex.Message);
            }
            finally
            {
             //   rfidMessage.button_Disconnect_TCP_Click(objreader);
            }
            */
            try
            {

                string data = "EA AB 34 00 00 00 00 7E 00 00 00 7E 00 00 00 01";
                string hexString = Convert.ToString(Convert.ToInt32(coderfid), 16);
                // 因为最后一个部分后面没有空格，所以最后一个元素会被截断。我们可以手动添加
                // 分割字符串

                string outStr = string.Empty;
                string outStrLast = string.Empty;
                rfidMessage.button_Disconnect_TCP_Click(objreader);
                Thread.Sleep(200);
                //读取标签内存
                rfidMessage.button_Connect_TCP_Click(objreader, Port.ToString(), IpAddress);
                Thread.Sleep(200);
                rfidMessage.ReadRFID(objreader, out outStr, "EPC区");
                Thread.Sleep(200);
                rfidMessage.button_Disconnect_TCP_Click(objreader);
                if (outStr == "")
                {
                    rs1.Status = false;
                    rs1.Message = "没有读取到标签";
                    return Json(rs1);
                }


                data = outStr;
                string[] parts = data.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries); // 使用空格分割并移除空项
                string originalString = string.Join(" ", parts); // 重新组合成一个字符串
                string replacement = hexString.PadLeft(8, '0').ToUpper(); ; // 替换的字符串

                string str = FormatHexString(replacement);

                int startIndex = 0; // 起始索引（注意：基于0开始）
                int length = 11; // 需要替换的长度

                // 删除原有的部分并插入新的字符串
                string newString = originalString.Remove(startIndex, length + 1);

                // string newString1 = "EA AB 34 00 00 00 00 7E 00 00 00 7E 00 00 00 01";// newString.Insert(startIndex, replacement);
                string newString1 = newString.Insert(startIndex, "" + str + " ");


                //写入标签内存

                Thread.Sleep(200);
                rfidMessage.button_Connect_TCP_Click(objreader, Port.ToString(), IpAddress);
                Thread.Sleep(200);
                rfidMessage.button_accessExec_Click(objreader, newString1);
                Thread.Sleep(200);
                rfidMessage.button_Disconnect_TCP_Click(objreader);
                Thread.Sleep(200);
                //读取标签内存
                rfidMessage.button_Connect_TCP_Click(objreader, Port.ToString(), IpAddress);
                Thread.Sleep(200);

                rfidMessage.ReadRFID(objreader, out outStrLast, "EPC区");
                Thread.Sleep(200);

                rfidMessage.button_Disconnect_TCP_Click(objreader);

                if (outStrLast == newString1)
                {
                    rs = await userService.PlcToolRFIDNoSend(pLAN_WORK);
                    var li190 = await _service.FindAsync<EQU_PLCConfig>(t => (t.PlcNameZH == "对刀仪准备启动BT40" || t.PlcNameZH == "对刀仪准备启动A63") && t.DbBlockType == "Send");
                    var eQU_TOOLMeasure = await _service.FindAsyncFirst<EQU_TOOL_Measure>(t => t.tool_name != null);
                    var eQU_TOOL = await _service.FindAsyncFirst<EQU_TOOL>(t => t.Identifier == pLAN_WORK.Identifier && t.program_seq == pLAN_WORK.program_seq);
                    if (eQU_TOOLMeasure != null && eQU_TOOLMeasure.RfidCode == eQU_TOOL.RfidCode && eQU_TOOL != null)
                    {
                    }
                    else
                    {
                        rs = await userService.PlcToolRFIDNoSend(pLAN_WORK);
                    }
                    if (rs != null && rs.Status == true)
                    {
                        userService.SetToolPlcPaly(eQU_TOOL, li190);
                        rs1.Status = true;
                        rs1.Message = "写入成功";
                        rs1.Data = outStrLast;
                        rs.Status = true;
                        rs.Message = "写入成功";
                    }
                    else
                    {
                        rs1.Status = false;
                        rs1.Message = "写入失败";
                        rs1.Data = outStrLast;
                        rs.Status = false;
                        rs.Message = "写入失败";
                    }


                }
                else
                {

                    rs1.Status = false;
                    rs1.Message = "写入失败";
                    rs1.Data = outStrLast;
                    rs.Status = false;
                    rs.Message = "写入失败";


                }
                return Json(rs1);
            }
            catch (Exception ex)
            {
                Console.WriteLine("An error occurred: " + ex.Message);
            }
            finally
            {
                //   rfidMessage.button_Disconnect_TCP_Click(objreader);
            }

            return Json(rs1);
        }
        #endregion

        #region 
        /// <summary>
        ///  涛思数据Query Taosdata CNC Data
        /// </summary>
        /// <param name="dbName"></param>
        /// <param name="tableName"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [HttpPost, Route("TaosdataCNCQuery")]
        public async Task<IActionResult> TaosdataCNCQuery(string dbName= "tony", string tableName= "taos_test",string where="", int limit=1)
        {
         //   var dbName = "tony";
          //  var tableName = "taos_test";
            var rs = "Ok"; // 默认返回结果

            using (var db = TDenginePoolHelper.Create(AppSetting.TDengine.Ip, AppSetting.TDengine.Port, AppSetting.TDengine.Username, AppSetting.TDengine.Password))
            {
                // 创建数据库（如果不存在）
                // db.ExecuteNonQuery("CREATE DATABASE IF NOT EXISTS sensor_data");

                // 使用数据库
                //db.ExecuteNonQuery("USE tony");

                //// 创建表（如果不存在）
                //db.ExecuteNonQuery("CREATE TABLE IF NOT EXISTS temperature (" +
                //                  "ts TIMESTAMP, " +
                //                  "device_id NCHAR(50), " +
                //                  "value FLOAT)");

                //// 插入单条数据
                //db.ExecuteNonQuery("INSERT INTO temperature VALUES " +
                //                  $"('{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}', 'device_001', 25.3)");

                // 查询数据
                //var results = db.Query<dynamic>($"SELECT * FROM {dbName}.{tableName} order by ts desc LIMIT 2",
                //    reader => new {
                //        Timestamp = (DateTime)reader.GetValue(0)

                //    });
                //var results = db.Query<LargeData>($"SELECT * FROM {dbName}.{tableName} order by ts desc LIMIT 2",
                //    reader=>new LargeData { });
                var results = db.Query<LargeData>($"SELECT * FROM {dbName}.{tableName} where 1=1 {where} order by ts desc LIMIT {limit}");
                // 处理查询结果
                rs=results.ListToJson();
            }

           
           

            return Json(rs);
        }
        /// <summary>
        /// 涛思数据测试CNC
        /// </summary>
        /// <returns></returns>       
        [HttpPost, Route("TaosdataCNC")]
        public async Task<IActionResult> TaosdataCNC([FromBody] List<LargeData> largeDatalist)
        {
            var dbName = "tony";
            var tableName = "taos_test";
            var rs = "Ok"; // 默认返回结果
            //var connectionString = $"host={ip};port={port};username={username};password={password}";

            // 从配置文件获取连接配置

            using (var db = TDenginePoolHelper.Create(AppSetting.TDengine.Ip, AppSetting.TDengine.Port, AppSetting.TDengine.Username, AppSetting.TDengine.Password))
            {
                // 创建数据库（如果不存在）
                // db.ExecuteNonQuery("CREATE DATABASE IF NOT EXISTS sensor_data");

                // 使用数据库
                //db.ExecuteNonQuery("USE tony");

                //// 创建表（如果不存在）
                //db.ExecuteNonQuery("CREATE TABLE IF NOT EXISTS temperature (" +
                //                  "ts TIMESTAMP, " +
                //                  "device_id NCHAR(50), " +
                //                  "value FLOAT)");

                //// 插入单条数据
                //db.ExecuteNonQuery("INSERT INTO temperature VALUES " +
                //                  $"('{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}', 'device_001', 25.3)");

                // 查询数据
                //var results = db.Query<dynamic>($"SELECT * FROM {dbName}.{tableName} order by ts desc LIMIT 2",
                //    reader => new {
                //        Timestamp = (DateTime)reader.GetValue(0)

                //    });
                //var results = db.Query<LargeData>($"SELECT * FROM {dbName}.{tableName} order by ts desc LIMIT 2",
                //    reader=>new LargeData { });
                var results = db.Query<LargeData>($"SELECT * FROM {dbName}.{tableName} order by ts desc LIMIT 2");
                // 处理查询结果
                foreach (var record in results)
                {
                    Console.WriteLine($"[{record.Ts}]");
                }
            }

            var connectionString1 = $"host={AppSetting.TDengine.Ip};port={AppSetting.TDengine.Port};username={AppSetting.TDengine.Username};password={AppSetting.TDengine.Password}";
            //using (var client = DbDriver.Open(new ConnectionStringBuilder(connectionString)))
            using (var client = DbDriver.Open(new ConnectionStringBuilder(connectionString1)))
            {
                Console.WriteLine("Connected");
                // 确保表存在
                EnsureTableExists(client, dbName, tableName);

                Stopwatch stopwatch = Stopwatch.StartNew();
                int totalCount = 0;

                foreach (var largeData in largeDatalist)
                {
                    totalCount++;

                    if (totalCount % 10000 == 0)
                    {
                        Console.WriteLine($"Has read {totalCount} lines, elapsed time {stopwatch.Elapsed.TotalSeconds} seconds");
                    }

                    var sql = GetInsertSql(largeData, dbName, tableName);

                    try
                    {
                        var affectRow = client.Exec(sql);
                        if (affectRow <= 0)
                        {
                            Console.WriteLine($"Affected row: {affectRow}");
                        }
                       // SelectData(client, dbName, tableName); // 可选：读取数据以验证插入是否成功
                        var dataList = SelectData(client, dbName, tableName,1);
                        Console.WriteLine();


                    }
                    catch (Exception e)
                    {
                        rs = "Error";
                        Console.WriteLine($"Error: {e.Message}");
                        break; // 可根据需要决定是否中断循环
                    }
                }

                Console.WriteLine($"Finish, elapsed total seconds: {stopwatch.Elapsed.TotalSeconds}");
            }

            return Json(rs);
        }
        #region 涛思数据辅助方法
        public static void SelectData(ITDengineClient client, string dbName, string tableName)
        {
            VOL.Core.Utilities.TDengineHelper dengineHelper = new VOL.Core.Utilities.TDengineHelper("",0,"","");
      
            string selectTable = $"SELECT * FROM {dbName}.{tableName} order by ts desc LIMIT 2";
            using (var rows = client.Query(selectTable))
            {
                while (rows.Read())
                {
                    var ts = (DateTime)rows.GetValue(0);
                    //var batcode = (string)rows.GetValue(1);
                    //var ordercode = (int)rows.GetValue(2);
                    //var program = (float)rows.GetValue(3);
                    var batcode = Encoding.UTF8.GetString((byte[])rows.GetValue(1));
                    var ordercode = Encoding.UTF8.GetString((byte[])rows.GetValue(2));
                    var program = Encoding.UTF8.GetString((byte[])rows.GetValue(3));
                    var cncNo = Encoding.UTF8.GetString((byte[])rows.GetValue(4));
                    var toolName = Encoding.UTF8.GetString((byte[])rows.GetValue(5));
                    var toolSpeed = (float)rows.GetValue(6);
                    var toolLoad = (float)rows.GetValue(7);
                    Console.WriteLine(
                          $"ts: {ts:yyyy-MM-dd HH:mm:ss.fff}, current: {batcode}, voltage: {ordercode}, phase: {program}, location: {program}");
                }
            }
        }
        public static List<LargeData> SelectData(ITDengineClient client, string dbName, string tableName,int limit=1)
        {
            var resultList = new List<LargeData>();
            string selectTable = $"SELECT * FROM {dbName}.{tableName} order by ts desc LIMIT {limit}";

            using (var rows = client.Query(selectTable))
            {
                while (rows.Read())
                {
                    var data = new LargeData
                    {
                        Ts = (DateTime)rows.GetValue(0),
                        BatCode = Encoding.UTF8.GetString((byte[])rows.GetValue(1)),
                        OrderCode = Encoding.UTF8.GetString((byte[])rows.GetValue(2)),
                        ProgramName = Encoding.UTF8.GetString((byte[])rows.GetValue(3)),
                        CNCNo = Encoding.UTF8.GetString((byte[])rows.GetValue(4)),
                        ToolName = Encoding.UTF8.GetString((byte[])rows.GetValue(5)),
                        ToolSpeed = (float)rows.GetValue(6),
                        ToolLoad = (float)rows.GetValue(7)
                    };
                    resultList.Add(data);
                }
            }

            return resultList;
        }
        /// <summary>
        /// drop table
        /// </summary>
        /// <param name="client"></param>
        /// <param name="dbName"></param>
        /// <param name="tableName"></param>
        private void TaosdatTableDrop(ITDengineClient client, string dbName, string tableName)
        {
            var dropTableSql = $"DROP TABLE IF EXISTS {dbName}.{tableName};";
            var affectRow = client.Exec(dropTableSql);
            if (affectRow > 0)
            {
                Console.WriteLine("Drop table success!");
            }
        }
        /// <summary>
        /// exit table
        /// </summary>
        /// <param name="client"></param>
        /// <param name="dbName"></param>
        /// <param name="tableName"></param>
        private void EnsureTableExists(ITDengineClient client, string dbName, string tableName)
        {
            var createTableSql = $@"
        CREATE TABLE IF NOT EXISTS {dbName}.{tableName}(
            ts TIMESTAMP,
            batcode VARCHAR(50),
            ordercode VARCHAR(50),
            programname VARCHAR(50),
            cncNo VARCHAR(50),
            toolName VARCHAR(50),           
            ToolSpeed float,
            ToolLoad float
        );
    ";
            var affectRow = client.Exec(createTableSql);
            if (affectRow > 0)
            {
                Console.WriteLine("Create table success!");
            }
        }

        private string GetInsertSql(LargeData largeData, string dbName, string tableName)
        {
            return $@"
        INSERT INTO {dbName}.{tableName} VALUES(
            '{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffffff")}',            
            '{largeData.BatCode}',
            '{largeData.OrderCode}',
            '{largeData.ProgramName}',
            '{largeData.CNCNo}',
            '{largeData.ToolName}',
           '{largeData.ToolSpeed}',
           '{largeData.ToolLoad}'
        );
    ";
        }

        #endregion
        /// <summary>
        /// 涛思数据测试
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("TestTaosdata")]
        public async Task<IActionResult> TestTaosdata()
        {
            var rs = string.Empty;
            // See https://aka.ms/new-console-template for more information

            Console.WriteLine("Hello, World!");
            //var ip = "192.168.28.181";
            var ip = "192.168.110.183";
            //var builder = new ConnectionStringBuilder("host=192.168.110.183;port=6030;username=root;password=taosdata");
            var builder = new ConnectionStringBuilder($"host={ip};port=6030;username=root;password=taosdata");
            using (var client = DbDriver.Open(builder))
            {
                Console.WriteLine("connected");

                var affectRow = client.Exec(@"create TABLE IF NOT exists tony.taos_test(
                                    ts timestamp,
                                    batcode varchar(50),
                                    ordercode varchar(50),
                                    programname varchar(50)
                                    );");
                if (affectRow > 0)
                {
                    Console.WriteLine("create table success!");
                }

                string csvPath = "G:\\BatInfo_2021\\data.csv";
                //写入
                Stopwatch stopwatch = Stopwatch.StartNew();

                int count = 0;
                int totalCount = 0;
                for (int i = 0; i < 3; i++)
                {


                    {


                        count++;
                        totalCount++;



                        if (count >= 10000)
                        {
                            count = 0;
                            Console.WriteLine($"has read {totalCount} lines,ellapse time {stopwatch.ElapsedMilliseconds / (double)1000} seconds");
                        }

                        var batCodeStr = i;


                        var sql = @$"insert into tony.taos_test values(
                    '{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffffff")}',
                    '{batCodeStr}',
                    'ordercode{batCodeStr}',
                    'programe{batCodeStr}'
                 
                  )";

                        try
                        {
                            affectRow = client.Exec(sql);
                            if (affectRow <= 0) { Console.WriteLine($"affect row:{affectRow}"); }
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine($"Error:{e.Message}");
                        }
                    }
                }
                Console.WriteLine($"finish,ellapse total seconds:{stopwatch.ElapsedMilliseconds / (double)1000}");
            }

            double ConvertToDouble(string str, double defalutValue)
            {
                if (double.TryParse(str, out var v)) return v;

                return defalutValue;
            }

            return Json(rs);
        }
        #endregion

        #region
        /// <summary>
        /// CNC Connect机床
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("PlcCNC1")]
        public async Task<IActionResult> PlcCNC1()
        {

            var equFrist = await _service.FindAsyncFirst<EQU_EQUIPMENT>(t => t.EquipmentNameZH == "发那科");// userService.PlcWorkpieceRFID(pLAN_WORK);
            WebResponseContent rs = new WebResponseContent();
            CncConnectParam param = new CncConnectParam();
            param.Host = equFrist.host;
            param.Port = Convert.ToUInt16(equFrist.port);
            param.Timeout = 3;
            rs.Status = this.Connect(param);
            return Json(rs);
        }
        private bool Connect(CncConnectParam param)
        {
            string IpText = param.Host;
            ushort PortText = param.Port;
            int timeout = param.Timeout;
            ushort Flibhndl;

            // this.IpText =// IpText.Trim();
            //   this.PortText = PortText;
            short ret = Focas1.cnc_allclibhndl3(IpText, PortText, timeout, out Flibhndl);
            if (ret == Focas1.EW_OK)//连接成功
            {
                //IsConnected = true;
                //this.Flibhndl = Flibhndl;
                //if (_cncPositionDisposable == null)
                //{
                //    _cncPositionDisposable = Observable.Interval(TimeSpan.FromMilliseconds(1000)).Subscribe(s =>
                //    {
                //        try
                //        {
                //            _cncPositionSubject.OnNext(GetAxisPosition());
                //            Task.Run(() =>
                //            {
                //                var vl = GetMeasure();
                //                _cncMeasureSubject.OnNext(vl);
                //            });
                //        }
                //        catch (Exception)
                //        {

                //        }

                //    });
                //}
                //param.Flibhndl = Flibhndl;
                return true;
            }
            else
            {
                //param.Flibhndl = Flibhndl;
                //IsConnected = false;
                return false;
            }
        }
        #endregion



        #region
        /// <summary>
        /// order
        /// </summary>
        /// <param name="orderNo"></param>
        /// <param name="customerName"></param>
        /// <param name="status"></param>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet, Route("orders")]
        public IActionResult GetOrders([FromQuery] string? orderNo, [FromQuery] int? program_seq, [FromQuery] string? status, [FromQuery] int page = 1, [FromQuery] int pageSize = 10)
        {
            var orders =  _service.Find<EQU_TOOL>(t=>t.Identifier!=null).OrderByDescending(t=>t.Identifier).ToList();// MockDataService.GetOrders();

            // 应用过滤条件
            if (!string.IsNullOrEmpty(orderNo))
            {
                orders = orders.Where(o => o.Identifier.Contains(orderNo)).ToList();
            }
            if (program_seq!=null)
            {
                orders = orders.Where(o => o.program_seq==program_seq).ToList();
            }
            //if (!string.IsNullOrEmpty(customerName))
            //{
            //    orders = orders.Where(o => o.CustomerName.Contains(customerName)).ToList();
            //}
            //if (!string.IsNullOrEmpty(status))
            //{
            //    orders = orders.Where(o => o.Status == status).ToList();
            //}

            // 计算总数
            var total = orders.Count;

            // 应用分页
            var pagedOrders = orders
                .Skip((page - 1) * pageSize)
                .Take(pageSize)
                .ToList();

            // 移除明细数据，减少响应大小
           // pagedOrders.ForEach(o => o.Details.Clear());

            return Ok(new
            {
                data = pagedOrders,
                total,
                page,
                pageSize
            });
        }
        /// <summary>
        /// orderdetails
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet(), Route("{id}/details")]
        public IActionResult GetOrderDetails(string id, string dbName = "tony", string tableName = "taos_test", string where = "", [FromQuery] int limit = 1, [FromQuery] int page = 1, [FromQuery] int pageSize = 10)
        {
            EQU_TOOL firstTool = null;
            List<LargeData> results = null;
            EQU_EQUIPMENT_LOAD fristLoad = null;
            var isLoad=false;
            if (!string.IsNullOrEmpty(id))
            {
                var toolid = Guid.Parse(id);
                 firstTool = _service.Find<EQU_TOOL>(t => t.Identifier != null).OrderByDescending(t => t.Id ==toolid).FirstOrDefault();// MockDataService.GetOrders();
               
                where = $" and ToolName='{id}'";
            }
           // string dbName = "tony", string tableName = "taos_test",string where = "", int limit = 1
            using (var db = TDenginePoolHelper.Create(AppSetting.TDengine.Ip, AppSetting.TDengine.Port, AppSetting.TDengine.Username, AppSetting.TDengine.Password))
            {
                var sql = $"SELECT * FROM {dbName}.{tableName} where 1=1 {where} order by ts desc";
                if (limit !=0)
                {
                    sql += $" LIMIT {limit}";
                }
                
                 results = db.Query<LargeData>(sql);
                // 处理查询结果
              //  rs = results.ListToJson();
            }

            var details = results;// MockDataService.GetOrderDetails(id);
            if (details.Count > 0)
            {
                var cncNo= details.FirstOrDefault().CNCNo;
                var maxToolSpeed = (decimal)details.Max(t => t.ToolSpeed);
                fristLoad = _service.Find<EQU_EQUIPMENT_LOAD>(t => t.EquipmentNo == cncNo&&t.RotationalSpeed==maxToolSpeed).FirstOrDefault();
                              
                
                
                if (firstTool != null)
                {
                    if (fristLoad != null)
                    {
                        firstTool.MinToolLoad = fristLoad.MinToolLoad;
                        firstTool.MaxToolLoad = fristLoad.MaxToolLoad;
                    }
                    firstTool.ToolSpeed = maxToolSpeed;
                    _service.Update(firstTool);
                    _service.SaveChanges();
                    isLoad = true;
                }
            }
            if (!details.Any())
            {
                // return NotFound($"未找到订单 {id} 的明细数据");
                return Ok(new
                {
                    data = new List<LargeData>(),
                    total = 0,
                    isLoad,
                    page,
                    pageSize
                });
            }
            // 计算总数
            var total = details.Count;

            // 应用分页
            var pagedOrders = details.OrderByDescending(t=>t.Ts)
                .Skip((page - 1) * pageSize)
                .Take(pageSize)
                .ToList();
            return Ok(new
            {
                data = pagedOrders,
                isLoad,
                total,
                page,
                pageSize
            });
        }
        #endregion


        #region kafka
        [HttpGet, Route("TestkafkaConsumer")]
        public IActionResult TestkafkaConsumer(string topic = "test")
        {
            var config = new ConsumerConfig
            {
                BootstrapServers = "192.168.110.183:9092",
                GroupId = "test-group",
                AutoOffsetReset = AutoOffsetReset.Earliest
            };

            using (var consumer = new ConsumerBuilder<Ignore, string>(config).Build())
            {
                consumer.Subscribe(topic);

                try
                {
                    while (true)
                    {
                        var consumeResult = consumer.Consume();
                        Console.WriteLine($"Received message at {consumeResult.TopicPartitionOffset}: {consumeResult.Message.Value}");
                    }
                }
                catch (OperationCanceledException)
                {
                    // Proper shutdown.
                    consumer.Close();
                }
            }

            return Ok("Messages sent to Kafka successfully.");
        }
        /// <summary>
        /// TestkafkaPro  
        /// </summary>
        /// <returns></returns>
        [HttpGet, Route("TestkafkaPro")]
        public async Task<IActionResult> TestkafkaPro(string topic = "test")
        {
            var config = new ProducerConfig { BootstrapServers = "192.168.110.183:9092" };

            using (var producer = new ProducerBuilder<Null, string>(config).Build())
            {
                try
                {
                    for (int i = 0; i < 2; i++)
                    {
                        string message = $"Hello Kafka {i}";
                        var result = await producer.ProduceAsync(topic, new Message<Null, string> { Value = message });

                        Console.WriteLine($"Delivered '{result.Value}' to '{result.TopicPartitionOffset}'");
                    }
                }
                catch (ProduceException<Null, string> e)
                {
                    Console.WriteLine($"Delivery failed: {e.Error.Reason}");
                }
            }
            return Ok("Messages sent to Kafka successfully.");
        }
        /// <summary>
        /// 测试Kafka消费者
        /// </summary>
        /// <param name="orderNo"></param>
        /// <returns></returns>
        [HttpGet, Route("TestKafka")]
        public IActionResult TestKafka([FromQuery] string? orderNo)
        {
            var rs = "";
            var config = new ConsumerConfig
            {
                BootstrapServers = "192.168.110.183:9092", // Kafka broker地址
                GroupId = "test-group",             // 消费者组ID
                AutoOffsetReset = AutoOffsetReset.Earliest // 从最早的消息开始消费
            };

            using (var c = new ConsumerBuilder<Ignore, string>(config).Build())
            {
                c.Subscribe("test"); // 订阅主题

                try
                {
                    while (true)
                    {
                        var cr = c.Consume(); // 阻塞直到有消息可消费
                        Console.WriteLine($"Received message at {cr.TopicPartitionOffset}: {cr.Message.Value}");
                    }
                }
                catch (OperationCanceledException)
                {
                    // 处理取消操作，例如用户按下Ctrl+C时
                }
                finally
                {
                    c.Close(); // 关闭消费者以清理资源
                }
            }

            return Ok(new
            {
                rs
            });
        }
        #endregion
        #region mqtt
        
        /// <summary>
        /// mqtt
        /// </summary>
        /// <param name="topic"></param>
        /// <param name="msginput"></param>
        /// <returns></returns>
        [HttpGet, Route("mqtt")]
        public async Task<IActionResult> mqtt(string topic555 = "sensor/2/temperature", string msginput = "test")
        {
            //初始化
            var mqtt = new MqttClientBase(new MqttClientBaseOptions()
            {
                clientId = "mqttx_fb4152ee",
                //username = "username",
                //password = "password",
                server = "broker.emqx.io",
                port = 1883
            });

            //断开连接事件
            mqtt.DisconnectedAsync((e) => {
                Console.WriteLine("连接断开");

                //重连服务器
                mqtt.ReConnect();
            });

            //连接服务器
            mqtt.Connect((args) => {
                /* 连接成功事件 */

                Console.WriteLine("连接成功");


                // 添加主题订阅，建议写到 连接成功事件 里面，这样重连后可以重新订阅主题
                mqtt.AddTopic("topic-1").Wait();
                mqtt.AddTopic("topic-2").Wait();
                mqtt.AddTopic("topic-3").Wait();

                // 取消主题订阅
                mqtt.DeleteTopic("topic-3").Wait();

                // 向指定主题推送消息
                mqtt.Publish("topic-1", "666666666").Wait();


             
                // 收到来自服务器的消息 topic：主题  msg：消息内容
                mqtt.Message((topic1, msg) => {


                    Console.WriteLine($"收到消息：{topic1}:{msg}");
                });

            });

            //Thread.Sleep(2000);
            //Task.Delay(3000).Wait();
            //// 收到来自服务器的消息 topic：主题  msg：消息内容
            //mqtt.Message((topic1, msg) => {

             
            //    Console.WriteLine($"收到消息：{topic1}:{msg}");
            //});

            // 这里暂停三秒，看三秒后主动断开连接效果
            // Task.Delay(3000).Wait();

            // 主动断开连接
            //mqtt.Disconnect();


            //while (true)
            //{
            //    // 向指定主题推送消息
            //    mqtt.Publish("topic-1", Console.ReadLine());
            //}

            return Ok("");
        }
            /// <summary>
            /// TestmqttServer
            /// </summary>
            /// <param name="topic"></param>
            /// <returns></returns>
            [HttpGet, Route("TestmqttServer")]
        public async Task<IActionResult> TestmqttServer(string topic= "sensor/2/temperature",string msginput="test")
        {
            string log = string.Empty;
          
            var options = new MqttClientOptionsBuilder().
                WithTcpServer("broker.emqx.io", Convert.ToInt32("1883"))
                .WithClientId("mqttx_fb4152ee")
                .Build();
            var result = await _client.ConnectAsync(options, CancellationToken.None);
            if (result.ResultCode == MqttClientConnectResultCode.Success)
            {
                log = DateTime.Now.ToString() + "    连接成功" + Environment.NewLine + log;
            }

            var msg = new MqttApplicationMessage();
            msg.Topic = topic;
            msg.PayloadSegment = Encoding.UTF8.GetBytes(msginput);
            msg.Retain = true;// isSave.IsChecked ?? false;
            MqttQualityOfServiceLevel level;
            switch (0)
            {
                case 0:
                    level = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce;
                    break;
                case 1:
                    level = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce;
                    break;
                case 2:
                    level = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce;
                    break;
                default:
                    throw new Exception("请选择服务质量");
            }

            msg.QualityOfServiceLevel = level;
            var resultPublish = await _client.PublishAsync(msg, CancellationToken.None);
            if (resultPublish.IsSuccess == true)
            {
                log = DateTime.Now.ToString() + "    发送成功" + Environment.NewLine + log;
            }
            else
            {
                log = DateTime.Now.ToString() + "    发送失败" + Environment.NewLine + log;
            }
            return Ok("");
        }
            /// <summary>
            /// mqtt
            /// </summary>
            /// <param name="topic"></param>
            /// <returns></returns>
            [HttpGet, Route("Testmqtt")]
        public async Task<IActionResult> Testmqtt(string topic = "sensor/2/temperature", string msginput = "test")
        {

            var msg = new MqttApplicationMessage();
            msg.Topic = topic;
            msg.PayloadSegment = Encoding.UTF8.GetBytes(msginput);
            msg.Retain = true;// isSave.IsChecked ?? false;
            MqttQualityOfServiceLevel level;
            switch (0)
            {
                case 0:
                    level = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce;
                    break;
                case 1:
                    level = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce;
                    break;
                case 2:
                    level = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce;
                    break;
                default:
                    throw new Exception("请选择服务质量");
            }

            msg.QualityOfServiceLevel = level;
            if(_client.IsConnected==false)
            {
                var options = new MqttClientOptionsBuilder().
               WithTcpServer("broker.emqx.io", Convert.ToInt32("1883"))
               .WithClientId("mqttx_fb4152ee")
               .Build();
                var result = await _client.ConnectAsync(options, CancellationToken.None);
            }
            //var resultPublish = await _client.PublishAsync(msg, CancellationToken.None);
            //if (resultPublish.IsSuccess == true)
            //{
            //    //this.log.Text = DateTime.Now.ToString() + "    发送成功" + Environment.NewLine + this.log.Text;
            //}
            //else
            //{
            //   // this.log.Text = DateTime.Now.ToString() + "    发送失败" + Environment.NewLine + this.log.Text;
            //}

            // 订阅消息
            var option = new MqttClientSubscribeOptions();

           // MqttQualityOfServiceLevel level;
            switch (0)
            {
                case 0:
                    level = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce;
                    break;
                case 1:
                    level = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce;
                    break;
                case 2:
                    level = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce;
                    break;
                default:
                    throw new Exception("请选择服务质量");
            }

            option.TopicFilters = new List<MqttTopicFilter>()
    {
        new MqttTopicFilter()
        {
            Topic =topic,// this.subscribeTopic.Text,
            QualityOfServiceLevel = level
        }
    };
            this._client.SubscribeAsync(option, CancellationToken.None);

             //// 将订阅的消息回显到日志区
            this._client.ApplicationMessageReceivedAsync += _client_ApplicationMessageReceivedAsync;


           
         
            return Ok("Messages sent to Kafka successfully.");
        }

        private Task _client_ApplicationMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs arg)
        {
            try
            {
                var array = arg.ApplicationMessage.PayloadSegment.Array;
                if (array == null)
                {
                    return Task.CompletedTask;
                }
                else
                {
                    var str = Encoding.UTF8.GetString(array);
                }
            }
            catch (Exception)
            {

                throw new NotImplementedException();
            }
            
            return Task.CompletedTask;

            
        }
        #endregion
    }


    public class CncConnectParam
    {
        public string NcType { get; set; } = "";
        public string NCCardNoText { get; set; } = "";
        public string TimeOutText { get; set; } = "3";
        public string Host { get; set; } = "";
        public ushort Port { get; set; }
        public ushort Flibhndl { get; set; }
        public int Timeout { get; set; } = 3;


    }
    #region 
    public class MockDataService
    {
        private static readonly List<Order1> _orders = new()
        {
            new Order1
            {
                Id = 1,
                OrderNo = "ORD20240301001",
                CustomerName = "张三",
                OrderDate = DateTime.Parse("2024-03-01 10:00:00"),
                TotalAmount = 3098.00m,
                Status = "pending",
                Remark = "客户要求尽快发货",
                Details = new List<OrderDetail>
                {
                    new OrderDetail
                    {
                        Id = 1,
                        OrderId = 1,
                        ProductCode = "P001",
                        ProductName = "笔记本电脑",
                        Specification = "15.6英寸",
                        Unit = "台",
                        Quantity = 1,
                        UnitPrice = 2999.00m,
                        Amount = 2999.00m,
                        Remark = "标配"
                    },
                    new OrderDetail
                    {
                        Id = 2,
                        OrderId = 1,
                        ProductCode = "P002",
                        ProductName = "无线鼠标",
                        Specification = "黑色",
                        Unit = "个",
                        Quantity = 1,
                        UnitPrice = 99.00m,
                        Amount = 99.00m,
                        Remark = "赠品"
                    }
                }
            },
            new Order1
            {
                Id = 2,
                OrderNo = "ORD20240301002",
                CustomerName = "李四",
                OrderDate = DateTime.Parse("2024-03-01 11:30:00"),
                TotalAmount = 5999.00m,
                Status = "paid",
                Remark = "已确认付款",
                Details = new List<OrderDetail>
                {
                    new OrderDetail
                    {
                        Id = 3,
                        OrderId = 2,
                        ProductCode = "P003",
                        ProductName = "平板电脑",
                        Specification = "12.9英寸",
                        Unit = "台",
                        Quantity = 1,
                        UnitPrice = 5999.00m,
                        Amount = 5999.00m,
                        Remark = "高配版"
                    }
                }
            },
            new Order1
            {
                Id = 3,
                OrderNo = "ORD20240301003",
                CustomerName = "王五",
                OrderDate = DateTime.Parse("2024-03-01 14:20:00"),
                TotalAmount = 1999.00m,
                Status = "shipped",
                Remark = "已安排发货",
                Details = new List<OrderDetail>
                {
                    new OrderDetail
                    {
                        Id = 4,
                        OrderId = 3,
                        ProductCode = "P004",
                        ProductName = "智能手表",
                        Specification = "42mm",
                        Unit = "个",
                        Quantity = 1,
                        UnitPrice = 1999.00m,
                        Amount = 1999.00m,
                        Remark = "运动版"
                    }
                }
            }
        };

        public static List<Order1> GetOrders()
        {
            return _orders;
        }

        public static Order1? GetOrderById(int id)
        {
            return _orders.FirstOrDefault(o => o.Id == id);
        }

        public static List<OrderDetail> GetOrderDetails(int orderId)
        {
            var order = GetOrderById(orderId);
            return order?.Details ?? new List<OrderDetail>();
        }
    }

    public class Order1
    {
        public int Id { get; set; }
        public string OrderNo { get; set; } = string.Empty;
        public string CustomerName { get; set; } = string.Empty;
        public DateTime OrderDate { get; set; }
        public decimal TotalAmount { get; set; }
        public string Status { get; set; } = string.Empty;
        public string Remark { get; set; } = string.Empty;
        public List<OrderDetail> Details { get; set; } = new List<OrderDetail>();
    }

    public class OrderDetail
    {
        public int Id { get; set; }
        public int OrderId { get; set; }
        public string ProductCode { get; set; } = string.Empty;
        public string ProductName { get; set; } = string.Empty;
        public string Specification { get; set; } = string.Empty;
        public string Unit { get; set; } = string.Empty;
        public int Quantity { get; set; }
        public decimal UnitPrice { get; set; }
        public decimal Amount { get; set; }
        public string Remark { get; set; } = string.Empty;
    }
    #endregion

    #region mqtt


    public class MqttClientBaseOptions
    {
        public string clientId { get; set; } = "client-1";
     public string username { get; set; } = "username";
        public string password { get; set; } = "password";
        public string server { get; set; } = "127.0.0.1";
        public int port { get; set; } = 10883;
    }

    /// <summary>
    /// Mqtt客户端
    /// </summary>
    public class MqttClientBase
    {
        /// <summary>
        /// 客户端
        /// </summary>
        public IMqttClient client;


        /// <summary>
        /// 订阅主题列表
        /// </summary>
        public List<string> Topics = new List<string>();



        public MqttClientOptions options;


         public MqttClientBaseOptions _opt;


        /// <summary>
        /// 主动断开连接
        /// </summary>
        public bool off = false;
        public bool isconn = false;


        /// <summary>
        /// 创建mqtt客户端，并值接传入初始参数
        /// </summary>
        /// <param name="opt"></param>
        public MqttClientBase(MqttClientBaseOptions opt)
        {
            this._opt = opt;


            //创建客户端
            client = new MqttFactory().CreateMqttClient();

            options = new MqttClientOptions()
            {
                ClientId = _opt.clientId,
                ChannelOptions = new MqttClientTcpOptions()
                {
                    Server = _opt.server,
                    Port = _opt.port,
                },

                Credentials = new MqttClientCredentials(_opt.username, Encoding.UTF8.GetBytes(_opt.password)),

                //清理会话
                CleanSession = false,

                //设置心跳
                KeepAlivePeriod = TimeSpan.FromSeconds(30)
            };
        }

        /// <summary>
        /// 创建mqtt客户端，不传参数，
        /// 必须在调用 Connect之前调用过SetOption方法
        /// </summary>
        public MqttClientBase()
        {
            //创建客户端
            client = new MqttFactory().CreateMqttClient();
        }

        /// <summary>
        /// 设置参数
        /// </summary>
        /// <param name="opt"></param>
        public void SetOption(MqttClientBaseOptions opt)
        {
            options = new MqttClientOptions()
            {
                ClientId = _opt.clientId,
                ChannelOptions = new MqttClientTcpOptions()
                {
                    Server = _opt.server,
                    Port = _opt.port,
                },

                Credentials = new MqttClientCredentials(_opt.username, Encoding.UTF8.GetBytes(_opt.password)),

                //清理会话
                CleanSession = false,

                //设置心跳
                KeepAlivePeriod = TimeSpan.FromSeconds(30)
            };
        }


        /// <summary>
        /// 连接服务器
        /// </summary>
        /// <param name="action">连接成功后执行</param>
        /// <param name="ConnectedAsync">连接成功事件</param>
        public void Connect(Action<MqttClientConnectedEventArgs> ConnectedAsync = null)
        {
            client.ConnectAsync(options);

            if (ConnectedAsync != null)
            {

                //连接成功事件
                client.ConnectedAsync += (args) =>
                {
                    ConnectedAsync(args);
                    return Task.CompletedTask;
                };

            }

        }

        /// <summary>
        /// 重连服务器
        /// 在连接断开事件中调用，即可实现无限轮询
        /// </summary>
        /// <param name="t">是否重复尝试重连</param>
        /// <param name="i">尝试次数</param>
        public void ReConnect()
        {
            try
            {
                client.ConnectAsync(options).Wait();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }


        public async Task AddTopic(string topic)
        {


            //更新订阅
            client.SubscribeAsync(new MqttClientSubscribeOptions()
            {
                TopicFilters = new List<MqttTopicFilter>() {
                    new MqttTopicFilter { Topic = topic }
                }
            });


            //将主题名称加入列表
            Topics.Add(topic);
        }

        /// <summary>
        /// 取消订阅
        /// </summary>
        /// <param name="topic"></param>
        /// <returns></returns>
        public async Task DeleteTopic(string topic)
        {
            client.UnsubscribeAsync(new MqttClientUnsubscribeOptions()
            {
                TopicFilters = new List<string> { topic }
            });
            Topics.Remove(topic);
        }

        /// <summary>
        /// 发布消息
        /// </summary>
        /// <param name="topic">主题</param>
        /// <param name="content">内容</param>
        /// <returns></returns>
        public async Task Publish(string topic, string content)
        {
            if (client.IsConnected)
            {
                client.PublishAsync(new MqttApplicationMessage()
                {
                    Topic = topic,
                    Payload = Encoding.UTF8.GetBytes(content)
                });
            }
        }



        /// <summary>
        /// 主动断开连接
        /// </summary>
        public void Disconnect()
        {
            off = true;
            client.DisconnectAsync();
        }

        /// <summary>
        /// 断开连接事件
        /// </summary>
        /// <param name="action"></param>
        /// <returns></returns>
        public async Task DisconnectedAsync(Action<MqttClientDisconnectedEventArgs> action)
        {
            client.DisconnectedAsync += (args) => {
                action(args);
                return Task.CompletedTask;
            };
        }



        /// <summary>
        /// 接收消息事件
        /// </summary>
        /// <param name="action"></param>
        /// <returns></returns>
        public async Task Message(Action<string, string> action)
        {

            client.ApplicationMessageReceivedAsync += (args) =>
            {
                var topic = args.ApplicationMessage.Topic;
                var array = args.ApplicationMessage.PayloadSegment.Array;//.BToString();
                var msg = string.Empty;
                if (array == null)
                {
                    return Task.CompletedTask;
                }
                else
                {
                    msg = Encoding.UTF8.GetString(array);
                }
                action(topic, msg);

                return Task.CompletedTask;
            };
        }



    }
    #endregion


    public class EventTest : INotification
    {
        public string UserName { get; set; }
    }
    public class EventHandle1:INotificationHandler<EQU_EQUIPMENT> {
       
        public Task Handle(EQU_EQUIPMENT notification, CancellationToken cancellationToken)
        {
            Console.WriteLine($"EventHandle1: {notification.EquipmentNameZH}{notification.EquipmentCode}");
            return Task.CompletedTask;
        }
    }

    /// <summary>
    /// 接收save
    /// </summary>
    public class UserAddHandle : INotificationHandler<UserAddedEvent>
    {
        public Task Handle(UserAddedEvent user, CancellationToken cancellationToken)
        {
            // 注：这里Item是 UserAddedEvent(UserInfo Item)中的参数
           // Console.WriteLine($"收到消息：用户新增成功，用户为:{user.EQU_EQUIPMENT.EquipmentNameZH},{user.EQU_EQUIPMENT.EquipmentCode}");
            return Task.CompletedTask;
        }
    }

}
